Skip to content

Commit 26c1e23

Browse files
committed
Updated solutions
1 parent a42f56a commit 26c1e23

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

Find Minimum in Rotated Sorted Array.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,53 @@ public int findMinSolutionTwo(int[] nums) {
5454
// Java expects a value to be returned even if conditions inside while-loop fails
5555
return 0;
5656
}
57+
58+
// SOLUTION 3
59+
public int findMinSolutionThree(int[] nums) {
60+
61+
/*
62+
* Time Complexity: O(log n) where n = length of nums. Nums is split by half until one element remains.
63+
* Then, the algorithm compares that one element in its half.
64+
*
65+
* Space Complexity: O(1) because no dynamic data structure or stack was created.
66+
*/
67+
68+
if (nums.length == 1) {
69+
return nums[0];
70+
}
71+
72+
// Create a return variable. This will hold the smallest element
73+
int res = nums[0];
74+
75+
// Create a left and right pointer
76+
int leftPtr = 0;
77+
int rightPtr = nums.length - 1;
78+
79+
// Iterate array
80+
while (leftPtr <= rightPtr) {
81+
82+
// If the array between left and right pointer is already sorted in ascending order, return the smallest value
83+
if (nums[leftPtr] < nums[rightPtr]) {
84+
res = Math.min(res, nums[leftPtr]);
85+
break;
86+
}
87+
88+
// Calculate middle index
89+
int midIdx = (int) rightPtr - leftPtr / 2;
90+
res = Math.min(res, nums[midIdx]);
91+
92+
// If left half of subarray is already sorted in ascending order, then move leftPtr to the right half to investigate the right side.
93+
// E.g., [3, 4, 5, 1, 2]
94+
if (nums[midIdx] >= nums[leftPtr]) {
95+
leftPtr = midIdx + 1;
96+
}
97+
else {
98+
// If right half of subarray is already sorted in ascending order, then move rightPtr to the left left half.
99+
// E.g., [1, 2, 3, 4, 5]
100+
rightPtr = midIdx - 1;
101+
}
102+
}
103+
104+
return res;
105+
}
57106
}

Remove Nth Node From End of List.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@
1414
class Solution {
1515
public ListNode removeNthFromEnd(ListNode head, int n) {
1616

17+
/*
18+
* Time Complexity: O(n) where n = length of linked list. We have to iterate the entire
19+
* list to find the nth to last node.
20+
*
21+
* Space Complexity: O(1) because no dynamic data structure was created. Only 3 nodes were
22+
* created and they take constant space to make.
23+
*/
24+
1725
// If head is empty or by itself, return null
1826
if (head == null || head.next == null) {
1927
return null;

0 commit comments

Comments
 (0)