Skip to content

Commit 30014aa

Browse files
committed
update- optimized LC#977 squares of array in sorted fashion, O(N) Time, O(n) Space
1 parent 7b674b8 commit 30014aa

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Leetcode/leetcodeTags/array/SquaresOfASortedArray977.java

+61
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package leetcodeTags.array;
22

3+
import java.util.ArrayList;
34
import java.util.Arrays;
45

56
public class SquaresOfASortedArray977 {
67

8+
// O(NlogN) time, O(N) space
79
public static int[] sortedSquares(int[] nums) {
810

911
int[] output = new int[nums.length];
@@ -16,9 +18,68 @@ public static int[] sortedSquares(int[] nums) {
1618
return output;
1719
}
1820

21+
// follow up part - O(N) Time | O(N) Space
22+
public static int[] sortedSquares2(int[] nums) {
23+
24+
ArrayList<Integer> list1 = new ArrayList<>(); // to store negative items
25+
ArrayList<Integer> list2 = new ArrayList<>(); // to store positive items
26+
int[] output = new int[nums.length]; // to store final sorted array
27+
28+
for (int n : nums) {
29+
if (n < 0) {
30+
list1.add(n);
31+
} else {
32+
list2.add(n);
33+
}
34+
}
35+
36+
int pos = 0; // position to fill in output array
37+
int ptr1 = list1.size() - 1, ptr2 = 0;
38+
39+
/*
40+
* here we traverse in reverse for list1 as it has negative elements in
41+
* sorted order and from beginning for list2 as it has positive elements
42+
*/
43+
while (ptr1 >= 0 && ptr2 < list2.size()) {
44+
if (Math.abs(list1.get(ptr1)) < Math.abs(list2.get(ptr2))) {
45+
output[pos] = list1.get(ptr1);
46+
ptr1--;
47+
} else {
48+
output[pos] = list2.get(ptr2);
49+
ptr2++;
50+
}
51+
pos++;
52+
}
53+
54+
// for remaining elements in either of two lists
55+
while (pos < output.length && ptr1 >= 0) {
56+
output[pos] = list1.get(ptr1);
57+
ptr1--;
58+
pos++;
59+
}
60+
while (pos < output.length && ptr2 < list2.size()) {
61+
output[pos] = list2.get(ptr2);
62+
ptr2++;
63+
pos++;
64+
}
65+
66+
// squaring the sorted elements
67+
for (int i = 0; i < output.length; i++) {
68+
output[i] = output[i] * output[i];
69+
}
70+
71+
return output;
72+
}
73+
1974
public static void main(String[] args) {
2075
System.out.println(Arrays.toString(sortedSquares(new int[] { -4, -1, 0, 3, 10 })));
2176
System.out.println(Arrays.toString(sortedSquares(new int[] { -7, -3, 2, 3, 11 })));
2277

78+
System.out.println("\ntesting optimal code\n");
79+
System.out.println(Arrays.toString(sortedSquares2(new int[] { -4, -1, 0, 3, 10 })));
80+
System.out.println(Arrays.toString(sortedSquares2(new int[] { -7, -3, 2, 3, 11 })));
81+
82+
int[] arr = { -10, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3 };
83+
System.out.println(Arrays.toString(sortedSquares2(arr)));
2384
}
2485
}

0 commit comments

Comments
 (0)