Workspace Reverse Pairs
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Reverse Pairs visualizer

Learn Reverse Pairs with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice optimization and matrix.

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 / 12Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    1,
    3,
    2,
    3,
    1
  ],
  "reverse": true
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,reverse
},s)=>{
let c=0;
function f(l,r){
if(l>=r)return;
let m=(l+r)>>1;
f(l,m);
f(m+1,r);
let j=m+1;
for(let i=l;
i<=m;
i++){
while(j<=r&&a[i]>(reverse?2*a[j]:a[j]))j++;
c+=j-m-1;
s("Count cross-half pairs",{
Array:a,Count:[c],Bounds:[l,m,r]
},[i])
}
let x=l,y=m+1,o=[];
while(x<=m||y<=r)o.push(y>r||x<=m&&a[x]<=a[y]?a[x++]:a[y++]);
a.splice(l,o.length,...o);
s("Merge halves",{
Array:a,Count:[c]
})
}
f(0,a.length-1);
return c
};

Execution canvas

Active Changed
STEP 1

Count cross-half pairs

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

Array5 items
Count1 items
Bounds3 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Arrays · Optimization and matrix

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

{
  "a": [
    1,
    3,
    2,
    3,
    1
  ],
  "reverse": true
}

Execution steps

  1. Count cross-half pairs
  2. Merge halves

Computed output

2
JavaScript reference implementation
const solve = ({
  a,reverse
},s)=>{
  let c=0;
  function f(l,r){
    if(l>=r)return;
    let m=(l+r)>>1;
    f(l,m);
    f(m+1,r);
    let j=m+1;
    for(let i=l;
    i<=m;
    i++){
      while(j<=r&&a[i]>(reverse?2*a[j]:a[j]))j++;
      c+=j-m-1;
      s("Count cross-half pairs",{
        Array:a,Count:[c],Bounds:[l,m,r]
      },[i])
    }
    let x=l,y=m+1,o=[];
    while(x<=m||y<=r)o.push(y>r||x<=m&&a[x]<=a[y]?a[x++]:a[y++]);
    a.splice(l,o.length,...o);
    s("Merge halves",{
      Array:a,Count:[c]
    })
  }
  f(0,a.length-1);
  return c
};

Continue learning

Practice related DSA questions in the same topic.