Workspace Squares Of A Sorted Array
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Squares of a Sorted Array visualizer

Learn Squares of a Sorted Array with a step-by-step Sliding Window & Two Pointers visualizer, JavaScript source code and a worked example. Practice opposing pointers.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 6Execution step
Reference example · JavaScript
Inspect reference input
[
  -4,
  -1,
  0,
  3,
  10
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let l=0,r=a.length-1,o=Array(a.length).fill(null);
for(let i=a.length-1;
i>=0;
i--){
if(Math.abs(a[l])>Math.abs(a[r]))o[i]=a[l++]**2;
else o[i]=a[r--]**2;
s("Place largest remaining square",{
Array:a,Output:o,Bounds:[l,r]
})
}
return o
};

Execution canvas

Active Changed
STEP 1

Place largest remaining square

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Array5 items
Output5 items
Bounds2 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Sliding Window & Two Pointers · Opposing pointers

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

[
  -4,
  -1,
  0,
  3,
  10
]

Execution steps

  1. Place largest remaining square

Computed output

[
  0,
  1,
  9,
  16,
  100
]
JavaScript reference implementation
const solve = (a,s)=>{
  let l=0,r=a.length-1,o=Array(a.length).fill(null);
  for(let i=a.length-1;
  i>=0;
  i--){
    if(Math.abs(a[l])>Math.abs(a[r]))o[i]=a[l++]**2;
    else o[i]=a[r--]**2;
    s("Place largest remaining square",{
      Array:a,Output:o,Bounds:[l,r]
    })
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.