Iterate negative part inverting it (change sing), then std::reverse it. Now std::inplace_merge two sorted parts of array. Finally square elements.
Time complexity: O(n)
Space complexity: O(1)
Alternative: Use two pointers, one at the beginning and one at the end of the input array. Compare the absolute values of the elements at the two pointers, square the larger one, and place it at the end of the result array. Move the corresponding pointer inward and repeat until the pointers meet.
Time complexity: O(n)
Space complexity: O(n)
Set ‘next’ and ‘curr’ pointers to the first element. Iterate ‘next’ over all values. If it points to value not equal to value pointed by ‘curr’, we found next ‘curr’, move ‘curr’ to next element and write ‘next’ value to it.
Time complexity: O(n)
Space complexity: O(1)
Alternative: Use std::unique
and
std::erase
.
Time complexity: O(n)
Space complexity: O(1)
Set two pointers “writer” and “reader” to beginning. Iterate reader over all elements. If it points to non-zero, swap elements and move writer to next position. Basically we rewrite each non-zero element, even if it was on the same place, skipping zero elements.
Time complexity: O(n)
Space complexity: O(1)
Alternative: Use std::remove
to
move non-zero elements to the beginning, then std::fill
the
remaining elements at the end with zeros.
Time complexity: O(n)
Space complexity: O(1)
Classic Solution: Use two pointers and scan strings backward, skipping backspaces and removed characters. You need to be very careful with edge cases.
Time complexity: O(N + M) where N and M are lengths of the strings.
Space complexity: O(1)
Alternative Solution: Create a helper function
applyBackspaces
which actually removes characters from the
string, moving them to the end of the string, similar to “Move Zeros”
with writer and reader pointers (move writer back if a backspace is
encountered). This is simpler and more elegant, but not optimal as you
have to change the string in-place, which might not be desired.
Time complexity: O(N + M)
Space complexity: O(1) (if in-place modification is allowed, otherwise O(N+M) for new strings)