Skip to content

Commit 1fcdd48

Browse files
Merge branch 'CodeHarborHub:main' into lc-sol-3033
2 parents 7761dfe + ef5aae5 commit 1fcdd48

File tree

3 files changed

+342
-0
lines changed

3 files changed

+342
-0
lines changed

assets/Avl-Tree.png

26.7 KB
Loading
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
---
2+
id: avl-tree-search
3+
title: AVL Tree Search (Geeks for Geeks)
4+
sidebar_label: AVL Tree Search
5+
tags:
6+
- Beginner
7+
- Search Algorithms
8+
- Geeks for Geeks
9+
- CPP
10+
- Python
11+
- Java
12+
- JavaScript
13+
- DSA
14+
description: "This is a solution to the AVL Tree Search problem on Geeks for Geeks."
15+
---
16+
17+
## What is AVL Tree Search?
18+
19+
AVL Tree Search is a search operation performed on an AVL tree, a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by no more than one, ensuring O(log N) time complexity for search operations.
20+
21+
## Algorithm for AVL Tree Search
22+
23+
1. Start at the root node of the AVL tree.
24+
2. Compare the target value with the value of the current node:
25+
- If the target value equals the current node's value, return the node.
26+
- If the target value is less than the current node's value, move to the left child.
27+
- If the target value is greater than the current node's value, move to the right child.
28+
3. Repeat step 2 until the target value is found or the current node becomes null.
29+
4. If the target value is not found, return null.
30+
31+
## How does AVL Tree Search work?
32+
33+
- It begins by comparing the target value to the value of the root node.
34+
- If the target value matches the root node's value, the search is complete.
35+
- If the target value is less than the root node's value, the search continues in the left subtree.
36+
- If the target value is greater than the root node's value, the search continues in the right subtree.
37+
- This process continues until the target value is found or a leaf node is reached without finding the target value.
38+
39+
![Example for AVL Tree Search(GFG)](../../assets/Avl-Tree.png)
40+
41+
## Problem Description
42+
43+
Given an AVL tree and a target element, implement the AVL Tree Search algorithm to find the node containing the target value in the tree. If the element is not present, return null.
44+
45+
## Examples
46+
47+
**Example 1:**
48+
```
49+
Input:
50+
AVL Tree:
51+
9
52+
/ \
53+
5 12
54+
/ \ \
55+
2 7 15
56+
57+
Target: 7
58+
Output: Node with value 7
59+
60+
```
61+
62+
## Your Task:
63+
64+
You don't need to read input or print anything. Complete the function avlTreeSearch() which takes the root of the AVL tree and a target value as input parameters and returns the node containing the target value. If the target value is not present in the tree, return null.
65+
66+
Expected Time Complexity: $O(LogN)$
67+
Expected Auxiliary Space: $O(1)$
68+
69+
## Constraints
70+
71+
- $1 <= Number of nodes <= 10^5$
72+
- $1 <= Node value <= 10^6$
73+
- $1 <= Target value <= 10^6$
74+
75+
## Implementation
76+
77+
<Tabs>
78+
79+
<TabItem value="C++" label="C++">
80+
<SolutionAuthor name="@ngmuraqrdd"/>
81+
```cpp
82+
#include <iostream>
83+
84+
struct AVLNode {
85+
int value;
86+
AVLNode* left;
87+
AVLNode* right;
88+
AVLNode(int val) : value(val), left(nullptr), right(nullptr) {}
89+
};
90+
91+
AVLNode* avlTreeSearch(AVLNode* root, int target) {
92+
AVLNode* current = root;
93+
while (current) {
94+
if (current->value == target) {
95+
return current;
96+
} else if (current->value < target) {
97+
current = current->right;
98+
} else {
99+
current = current->left;
100+
}
101+
}
102+
return nullptr;
103+
}
104+
105+
int main() {
106+
AVLNode* root = new AVLNode(9);
107+
root->left = new AVLNode(5);
108+
root->right = new AVLNode(12);
109+
root->left->left = new AVLNode(2);
110+
root->left->right = new AVLNode(7);
111+
root->right->right = new AVLNode(15);
112+
113+
int target = 7;
114+
AVLNode* result = avlTreeSearch(root, target);
115+
if (result) {
116+
std::cout << "Node with value " << result->value << " found." << std::endl;
117+
} else {
118+
std::cout << "Node not found." << std::endl;
119+
}
120+
121+
return 0;
122+
}
123+
124+
</TabItem>
125+
126+
<TabItem value="Java" label="Java">
127+
<SolutionAuthor name="@ngmuraqrdd"/>
128+
```java
129+
class AVLNode {
130+
int value;
131+
AVLNode left, right;
132+
AVLNode(int value) {
133+
this.value = value;
134+
left = right = null;
135+
}
136+
}
137+
138+
public class AVLTreeSearch {
139+
public static AVLNode avlTreeSearch(AVLNode root, int target) {
140+
AVLNode current = root;
141+
while (current != null) {
142+
if (current.value == target) {
143+
return current;
144+
} else if (current.value < target) {
145+
current = current.right;
146+
} else {
147+
current = current.left;
148+
}
149+
}
150+
return null;
151+
}
152+
153+
public static void main(String[] args) {
154+
AVLNode root = new AVLNode(9);
155+
root.left = new AVLNode(5);
156+
root.right = new AVLNode(12);
157+
root.left.left = new AVLNode(2);
158+
root.left.right = new AVLNode(7);
159+
root.right.right = new AVLNode(15);
160+
161+
int target = 7;
162+
AVLNode result = avlTreeSearch(root, target);
163+
if (result != null) {
164+
System.out.println("Node with value " + result.value + " found.");
165+
} else {
166+
System.out.println("Node not found.");
167+
}
168+
}
169+
}
170+
171+
```
172+
</TabItem>
173+
</Tabs>
174+
175+
## Complexity Analysis
176+
177+
- **Time Complexity**:$O(log n)$, where $n$ is the number of nodes in the AVL tree. The height of the tree is kept balanced, leading to logarithmic time complexity.
178+
- **Space Complexity**: $O(1)$, as no extra space is required apart from the input tree.
179+
180+
## Advantages and Disadvantages
181+
182+
**Advantages:**
183+
- Ensures balanced tree structure for efficient search, insert, and delete operations.
184+
- Fast search time due to logarithmic time complexity.
185+
186+
**Disadvantages:**
187+
- Requires additional rotations to maintain balance during insert and delete operations.
188+
- More complex to implement compared to simple binary search trees.
189+
190+
191+
## References
192+
193+
- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/practice-questions-height-balancedavl-tree//)
194+
- **Author's Geeks for Geeks Profile:** [MuraliDharan](https://www.geeksforgeeks.org/user/ngmuraqrdd/)
195+
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
---
2+
id: number-of-subarrays-that-match-a-pattern-i
3+
title: Number of Subarrays That Match a Pattern I (LeetCode)
4+
sidebar_label: 3034-NumberOfSubarraysThatMatchAPatternI
5+
tags:
6+
- Array
7+
- Pattern
8+
- Sliding Window
9+
description: Count the number of subarrays in an integer array that match a given pattern.
10+
sidebar_position: 3034
11+
---
12+
13+
## Problem Description
14+
15+
| Problem Statement | Solution Link | LeetCode Profile |
16+
| :---------------- | :------------ | :--------------- |
17+
| [Number of Subarrays That Match a Pattern I](https://leetcode.com/problems/number-of-subarrays-that-match-a-pattern-i/) | [Number of Subarrays That Match a Pattern I Solution on LeetCode](https://leetcode.com/problems/number-of-subarrays-that-match-a-pattern-i/solutions/) | [vaishu_1904](https://leetcode.com/u/vaishu_1904/) |
18+
19+
## Problem Description
20+
21+
You are given a 0-indexed integer array nums of size n, and a 0-indexed integer array pattern of size m consisting of integers -1, 0, and 1.
22+
23+
A subarray nums[i..j] of size m + 1 is said to match the pattern if the following conditions hold for each element pattern[k]:
24+
25+
- `nums[i + k + 1] > nums[i + k]` if `pattern[k] == 1`.
26+
- `nums[i + k + 1] == nums[i + k]` if `pattern[k] == 0`.
27+
- `nums[i + k + 1] < nums[i + k]` if `pattern[k] == -1`.
28+
29+
Return the count of subarrays in nums that match the pattern.
30+
31+
### Example 1
32+
33+
- **Input:** `nums = [1,2,3,4,5,6]`, `pattern = [1,1]`
34+
- **Output:** `4`
35+
- **Explanation:** The pattern `[1,1]` indicates that we are looking for strictly increasing subarrays of size 3. In the array `nums`, the subarrays `[1,2,3]`, `[2,3,4]`, `[3,4,5]`, and `[4,5,6]` match this pattern.
36+
Hence, there are 4 subarrays in `nums` that match the pattern.
37+
38+
### Example 2
39+
40+
- **Input:** `nums = [1,4,4,1,3,5,5,3]`, `pattern = [1,0,-1]`
41+
- **Output:** `2`
42+
- **Explanation:** Here, the pattern `[1,0,-1]` indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array `nums`, the subarrays `[1,4,4,1]`, and `[3,5,5,3]` match this pattern.
43+
Hence, there are 2 subarrays in `nums` that match the pattern.
44+
45+
### Constraints
46+
47+
- `2 <= n == nums.length <= 100`
48+
- `1 <= nums[i] <= 10^9`
49+
- `1 <= m == pattern.length < n`
50+
- `-1 <= pattern[i] <= 1`
51+
52+
## Approach
53+
54+
To solve this problem, we can use a sliding window approach to efficiently count the number of subarrays that match the given pattern. Here's the approach:
55+
56+
1. Iterate through the array with a sliding window of size `m+1`.
57+
2. For each window, check if the subarray matches the pattern.
58+
3. Increment the count if the subarray matches the pattern.
59+
60+
### Solution Code
61+
62+
#### Python
63+
64+
```python
65+
class Solution:
66+
def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int:
67+
n, m = len(nums), len(pattern)
68+
count = 0
69+
70+
for i in range(n - m):
71+
match = True
72+
for k in range(m):
73+
if (pattern[k] == 1 and nums[i + k + 1] <= nums[i + k]) or \
74+
(pattern[k] == 0 and nums[i + k + 1] != nums[i + k]) or \
75+
(pattern[k] == -1 and nums[i + k + 1] >= nums[i + k]):
76+
match = False
77+
break
78+
if match:
79+
count += 1
80+
81+
return count
82+
```
83+
84+
#### C++
85+
86+
```c++
87+
#include <vector>
88+
using namespace std;
89+
90+
class Solution {
91+
public:
92+
int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) {
93+
int n = nums.size(), m = pattern.size();
94+
int count = 0;
95+
96+
for (int i = 0; i <= n - m - 1; ++i) {
97+
bool match = true;
98+
for (int k = 0; k < m; ++k) {
99+
if ((pattern[k] == 1 && nums[i + k + 1] <= nums[i + k]) ||
100+
(pattern[k] == 0 && nums[i + k + 1] != nums[i + k]) ||
101+
(pattern[k] == -1 && nums[i + k + 1] >= nums[i + k])) {
102+
match = false;
103+
break;
104+
}
105+
}
106+
if (match) {
107+
count++;
108+
}
109+
}
110+
111+
return count;
112+
}
113+
};
114+
```
115+
116+
#### Java
117+
118+
```java
119+
class Solution {
120+
public int countMatchingSubarrays(int[] nums, int[] pattern) {
121+
int n = nums.length, m = pattern.length;
122+
int count = 0;
123+
124+
for (int i = 0; i <= n - m - 1; ++i) {
125+
boolean match = true;
126+
for (int k = 0; k < m; ++k) {
127+
if ((pattern[k] == 1 && nums[i + k + 1] <= nums[i + k]) ||
128+
(pattern[k] == 0 && nums[i + k + 1] != nums[i + k]) ||
129+
(pattern[k] == -1 && nums[i + k + 1] >= nums[i + k])) {
130+
match = false;
131+
break;
132+
}
133+
}
134+
if (match) {
135+
count++;
136+
}
137+
}
138+
139+
return count;
140+
}
141+
}
142+
```
143+
144+
### Conclusion
145+
The solutions use a sliding window approach to efficiently count the number of subarrays that match
146+
the given pattern. This ensures an efficient and straightforward way to solve the problem across
147+
different programming languages.

0 commit comments

Comments
 (0)