Skip to content

Commit ef8de7a

Browse files
committed
Update searchRotateSortedArray logic
1 parent 32b6e46 commit ef8de7a

File tree

4 files changed

+154
-35
lines changed

4 files changed

+154
-35
lines changed

src/javascript/algorithms/array/11.rotateArray/rotateArray.md

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,15 @@ Example 2:
1212
Input: nums = [-10, 4, 5, -1], n = 2
1313
Output: [5, -1, -10, 4]
1414

15+
Example 3 (Edge Case):
16+
17+
Input: nums = [1], n = 10
18+
Output: [1] (Single element array remains unchanged regardless of rotation count)
19+
1520
**Algorithm overview:**
21+
This problem can be solved using two different approaches:
22+
23+
### Approach 1: Reversal Technique (Efficient)
1624
This algorithm leverages the **reversal technique** (a two-pointer approach) to efficiently rotate the array in-place.
1725

1826
To rotate the array to the right by `n` steps:
@@ -26,14 +34,18 @@ To rotate the array to the right by `n` steps:
2634
1. **Calculate Array Length**
2735
Initialize a variable `length` to store the total number of elements in the array.
2836

29-
2. **Edge case**
30-
No rotation is required when the given array is empty and number of rotations is equals to the length of an array. This condition is helpful for early exit.
31-
37+
2. **Handle Edge Cases**
38+
No rotation is required when:
39+
- The array is empty
40+
- The rotation count is 0
41+
- The rotation count is equal to the array length (full rotation returns to original state)
42+
This condition is helpful for early exit.
43+
3244
3. **Normalize the Rotation Count**
3345
Update the rotation count by taking `n % length` to handle cases where `n` exceeds the array size. This ensures we perform only the necessary rotations.
3446

3547
4. **Define a Reversal Helper Function**
36-
Implement a helper function that reverses elements between two indices (`left` and `right`) in the array using a two-pointer technique. Swap the elements at `left` and `right`, then increment `left` and decrement `right` in each iteration until both pointers meet.
48+
Implement a helper function that reverses elements between two indices (`start` and `end`) in the array using a two-pointer technique. Swap the elements at `start` and `end`, then increment `start` and decrement `end` in each iteration until both pointers meet.
3749

3850
5. **Reverse the Entire Array**
3951
Apply the reversal function to the full array (from index `0` to `length - 1`). This step brings the elements that need to be rotated to the front, but in reverse order.
@@ -47,11 +59,40 @@ To rotate the array to the right by `n` steps:
4759
8. **Return the Rotated Array**
4860
The array has now been successfully rotated in-place and is ready for use.
4961

62+
### Approach 2: Brute Force Method
63+
This approach uses JavaScript's array methods to perform the rotation one step at a time.
64+
65+
#### Detailed steps:
66+
67+
1. **Calculate Array Length**
68+
Initialize a variable `length` to store the total number of elements in the array.
69+
70+
2. **Handle Empty Array**
71+
Return immediately if the array is empty.
72+
73+
3. **Normalize the Rotation Count**
74+
Update the rotation count by taking `n % length` to handle cases where `n` exceeds the array size.
75+
76+
4. **Perform Rotation**
77+
For each of the `n` steps:
78+
- Remove the last element of the array using `pop()`
79+
- Insert this element at the beginning of the array using `unshift()`
80+
81+
5. **Array is Rotated**
82+
After `n` iterations, the array has been rotated to the right by `n` positions.
83+
5084
## Time and Space Complexity
5185

86+
### Approach 1 (Reversal Technique):
5287
- **Time Complexity:** `O(n)`
5388
The algorithm performs three reverse operations, each taking `O(n)` time in total.
5489

5590
- **Space Complexity:** `O(1)`
5691
The rotation is done in-place, using only a constant amount of extra space regardless of input size.
5792

93+
### Approach 2 (Brute Force):
94+
- **Time Complexity:** `O(n²)`
95+
For each of the `n` rotations, the `unshift()` operation takes `O(n)` time as it requires shifting all elements.
96+
97+
- **Space Complexity:** `O(1)`
98+
The rotation is done in-place, modifying the original array.

src/javascript/algorithms/array/12.searchRotatedSortedArray/searchRotatedSortedArray.js

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,41 @@
1-
// TC: O(log n), SC: O(1)
1+
/**
2+
* Searches for a target in a rotated sorted array.
3+
* Returns the index of the target if found, otherwise -1.
4+
* Time Complexity: O(log n)
5+
* Space Complexity: O(1)
6+
*/
27
function searchRotatedSortedArray(nums, target) {
38
let left = 0;
49
let right = nums.length - 1;
510

6-
while(left <= right) {
7-
let mid = Math.floor(left + (right-left)/2);
8-
if(nums[mid] === target) {
9-
return mid;
10-
}
11+
while (left <= right) {
12+
const mid = Math.floor((left + right) / 2);
13+
14+
// Found the target
15+
if (nums[mid] === target) return mid;
1116

12-
if(nums[left] <= nums[mid]) { // Left to mid is sorted
13-
if(nums[left] <= target && target < nums[mid]) {
14-
right = mid - 1;
17+
// Determine which half is sorted
18+
if (nums[left] <= nums[mid]) {
19+
// Left side is sorted
20+
if (nums[left] <= target && target < nums[mid]) {
21+
right = mid - 1; // Target in left half
1522
} else {
16-
left = mid + 1;
23+
left = mid + 1; // Target in right half
1724
}
18-
} else { // Mid to right is sorted
19-
if(nums[mid] < target && target <= nums[right]) {
20-
left = mid + 1;
25+
} else {
26+
// Right side is sorted
27+
if (nums[mid] < target && target <= nums[right]) {
28+
left = mid + 1; // Target in right half
2129
} else {
22-
right = mid - 1;
30+
right = mid - 1; // Target in left half
2331
}
2432
}
2533
}
26-
return -1;
34+
35+
return -1; // Target not found
2736
}
2837

38+
2939
let nums = [3, 4, 5, 6, 7, 0, 1, 2];
3040
console.log(searchRotatedSortedArray(nums, 7));
3141

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,66 @@
11
**Description:**
2-
Given a sorted array `nums` in an ascending order, which is rotated at some known pivot index. You need to search for a given `target` value, if found in the array return it's index otherwise return -1.
2+
Given a sorted array `nums` in ascending order that has been rotated at an unknown pivot point, search for a target value. If the target is found in the array, return its index; otherwise, return -1.
33

4-
**Note:** There are no duplicate values exist. The runtime complexity should be O(log n).
4+
**Note:** The array contains no duplicate values. The solution should have a runtime complexity of O(log n).
55

66
### Examples
7-
87
Example 1:
8+
99
Input: nums = [3, 4, 5, 6, 7, 0, 1, 2], target = 7
1010
Output: 4
1111

1212
Example 2:
13+
1314
Input: nums = [3, 4, 5, 6, 7, 0, 1, 2], target = 9
1415
Output: -1
1516

16-
**Algorithmic Steps:**
17-
This problem is solved with the help of **binary search** technique. Since it is a rotated sorted array, there will be two subararys of elements in an ascending order. You can decide the presence of target element by verifying either in left side subarray or right side subarray. The algorithmic approach can be summarized as follows:
17+
Example 3 (Edge Case):
18+
19+
Input: nums = [1], target = 1
20+
Output: 0
21+
22+
**Algorithm overview:**
23+
This problem is solved using a modified **binary search** technique. In a rotated sorted array, there are two sorted subarrays. The key insight is to determine which subarray is sorted and then check if the target lies within that sorted portion.
24+
25+
#### Detailed steps:
1826

19-
1. Initialize left(`left`) and right pointers(`right`) to the beginning and ending index of an array.
27+
1. **Initialize Pointers**
28+
Set `left` pointer to the beginning (index 0) and `right` pointer to the end (index length-1) of the array.
2029

21-
2. Iterate over input array until either left pointer reaches right pointer or target element found.
30+
2. **Binary Search Loop**
31+
Continue searching while `left` pointer is less than or equal to `right` pointer.
2232

23-
3. Calculate the middle index of the array to divide into two equal subarrays.
33+
3. **Find Middle Element**
34+
Calculate the middle index using `mid = Math.floor((left + right) / 2)`.
2435

25-
4. If the middle element is equals to target, return the middle element index as output.
36+
4. **Check for Target Match**
37+
If the middle element equals the target (`nums[mid] === target`), return the middle index immediately.
2638

27-
5. If the left element is less than or equal to middle element(i.e, `nums[left] <= nums[mid]`), the left portion of input array is sorted. In this case, if the target element exists between left and middle elements, update the right pointer to the element before the middle element(`right = mid-1`). This logic indicates that target exists with in first subarray. Otherwise update the left pointer to the element just after the middle element(`left = mid+1`) to indicate the target exists with in second subarray.
39+
5. **Determine Which Half is Sorted**
40+
- If `nums[left] <= nums[mid]`, the left half is sorted.
41+
- Otherwise, the right half is sorted.
2842

29-
6. In the same way, if the right element is greater than or equal to right element(i.e, `nums[mid] <= nums[right]`), the right portion of input array is sorted. In this case, if the target element exists between right and middle elements, update the left pointer to the element after the middle element(`left = mid+1`). This logic indicates that target exists with in second subarray. Otherwise update the right pointer to the element just before the middle element(`right = mid-1`) to indicate the target exists with in first subarray.
43+
6. **Search in Sorted Half**
44+
- If the left half is sorted:
45+
- Check if the target is within the range `nums[left]` to `nums[mid-1]`.
46+
- If yes, search the left half by setting `right = mid - 1`.
47+
- If no, search the right half by setting `left = mid + 1`.
3048

31-
7. Repeat steps 4-6 element found or until end of array reached.
49+
- If the right half is sorted:
50+
- Check if the target is within the range `nums[mid+1]` to `nums[right]`.
51+
- If yes, search the right half by setting `left = mid + 1`.
52+
- If no, search the left half by setting `right = mid - 1`.
3253

33-
8. Return -1, if the target doesn't exist with in input array.
54+
7. **Repeat or Return**
55+
Repeat steps 3-6 until either the target is found or the search space is exhausted.
3456

57+
8. **Not Found Case**
58+
If the loop terminates without finding the target, return -1.
3559

36-
**Time and Space complexity:**
60+
## Time and Space Complexity
3761

38-
This algorithm has a time complexity of `O(log n)`, where `n` is the number of elements. This is because we divide the array into two subarrays each time and find the index of target element using binary search algorithm.
62+
- **Time Complexity:** `O(log n)`
63+
The algorithm uses a binary search approach, dividing the search space in half with each iteration. Even though the array is rotated, we can still determine which half to search in constant time.
3964

40-
Here, we don't use any additional datastructure other than two left pointer variables. Hence, the space complexity will be O(1).
65+
- **Space Complexity:** `O(1)`
66+
The algorithm uses only a constant amount of extra space regardless of input size, as it only requires a few variables (`left`, `right`, and `mid`) to track the search space.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
**Description:**
2+
Given an array of integers, find the third largest element in the array. If there are fewer than three unique elements, return a message indicating that there are not enough unique elements.
3+
4+
### Examples
5+
Example 1:
6+
7+
Input: [33, 90, 10, 50, 33, 77, 90, 4]
8+
Output: 50
9+
10+
Example 2:
11+
12+
Input: [1, 2]
13+
Output: "There are no 3 unique elements in an array"
14+
15+
**Algorithmic Steps**
16+
This problem can be solved using two different approaches:
17+
18+
**Approach 1: Single Pass Tracking**
19+
1. Initialize three variables to track the first, second, and third largest elements, all set to negative infinity.
20+
2. Iterate through each number in the array:
21+
- Skip if the number is equal to any of the three largest elements (to handle duplicates)
22+
- If the number is greater than the first largest, update all three variables accordingly
23+
- If the number is greater than the second largest but less than the first, update the second and third largest
24+
- If the number is greater than the third largest but less than the second, update only the third largest
25+
3. After the iteration, if the third largest is still negative infinity, return a message indicating there are not enough unique elements
26+
4. Otherwise, return the third largest element
27+
28+
**Approach 2: Using Set and Sort**
29+
1. Create a Set from the array to remove duplicates
30+
2. Convert the Set back to an array
31+
3. If the array length is less than 3, return a message indicating there are not enough unique elements
32+
4. Sort the array in descending order
33+
5. Return the element at index 2 (third element)
34+
35+
**Time and Space complexity:**
36+
**Approach 1 (Single Pass Tracking):**
37+
- Time Complexity: O(n), where n is the length of the array, as we only need to iterate through the array once.
38+
- Space Complexity: O(1), as we only use three variables regardless of the input size.
39+
40+
**Approach 2 (Using Set and Sort):**
41+
- Time Complexity: O(n log n), dominated by the sorting operation.
42+
- Space Complexity: O(n) for storing the unique elements in the Set.

0 commit comments

Comments
 (0)