This problem looks busy at first, but the accepted solution is built around one steady invariant. For 977. Squares of a Sorted Array, the solution in this repository is mainly a greedy solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: greedy.
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are sortedSquares.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(NlogN), where N is the length of A.
- Space: O(N).
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
03
04
05
06Example 1:
07
08Input: [-4,-1,0,3,10]
09Output: [0,1,9,16,100]
10Example 2:
11
12Input: [-7,-3,2,3,11]
13Output: [4,9,9,49,121]
14
15
16Note:
17
181 <= A.length <= 10000
19-10000 <= A[i] <= 10000
20A is sorted in non-decreasing order.
21**/
22
23//Runtime: 124 ms, faster than 100.00% of C++ online submissions for Squares of a Sorted Array.
24class Solution {
25public:
26 vector<int> sortedSquares(vector<int>& A) {
27 for(int i = 0; i < A.size(); i++){
28 A[i] *= A[i];
29 }
30
31 sort(A.begin(), A.end());
32
33 return A;
34 }
35};
36
37/**
38Approach 1: Sort
39Intuition and Algorithm
40
41Create an array of the squares of each element, and sort them.
42
43Complexity Analysis
44
45Time Complexity: O(NlogN), where N is the length of A.
46
47Space Complexity: O(N).
48**/
49
50/**
51Approach 2: Two Pointer
52Intuition
53
54Since the array A is sorted, loosely speaking it has some negative elements with squares in decreasing order, then some non-negative elements with squares in increasing order.
55
56For example, with [-3, -2, -1, 4, 5, 6], we have the negative part [-3, -2, -1] with squares [9, 4, 1], and the positive part [4, 5, 6] with squares [16, 25, 36]. Our strategy is to iterate over the negative part in reverse, and the positive part in the forward direction.
57
58Algorithm
59
60We can use two pointers to read the positive and negative parts of the array - one pointer j in the positive direction, and another i in the negative direction.
61
62Now that we are reading two increasing arrays (the squares of the elements), we can merge these arrays together using a two-pointer technique.
63**/
64
65/**
66//Runtime: 104 ms, faster than 100.00% of C++ online submissions for Squares of a Sorted Array.
67class Solution {
68public:
69 vector<int> sortedSquares(vector<int>& A) {
70 int N = A.size();
71 int forward = 0;
72 while(forward < N && A[forward] < 0){
73 forward++;
74 }
75 int backward = forward - 1;
76
77 //now A[forward] >=0 and A[backward] < 0
78
79 vector<int> ans(N);
80 int cursor = 0;
81
82 while(backward >= 0 && forward < N){
83 if(A[backward]*A[backward] < A[forward]*A[forward]){
84 ans[cursor++] = A[backward]*A[backward];
85 backward--;
86 } else{
87 ans[cursor++] = A[forward]*A[forward];
88 forward++;
89 }
90 }
91
92 while(backward >= 0){
93 ans[cursor++] = A[backward]*A[backward];
94 backward--;
95 }
96
97 while(forward < N){
98 ans[cursor++] = A[forward]*A[forward];
99 forward++;
100 }
101 return ans;
102 }
103};
104**/
105
106/**
107Complexity Analysis
108
109Time Complexity: O(N), where N is the length of A.
110
111Space Complexity: O(N).
112**/
Cost