Workspace Search In Rotated Sorted Array
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Search in Rotated Sorted Array visualizer

Learn Search in Rotated Sorted Array with a step-by-step Binary Search visualizer, JavaScript source code and a worked example. Practice sorted arrays.

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 / 4Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    4,
    5,
    6,
    7,
    0,
    1,
    2
  ],
  "k": 0,
  "dupes": false
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k,dupes
},s)=>{
let l=0,r=a.length-1;
while(l<=r){
let m=(l+r)>>1;
s("Identify sorted half",{
Array:a,Bounds:[l,m,r]
},[l,m,r]);
if(a[m]===k)return dupes?true:m;
if(a[l]===a[m]&&a[m]===a[r]){
l++;
r--
}else if(a[l]<=a[m]){
if(a[l]<=k&&k<a[m])r=m-1;
else l=m+1
}else{
if(a[m]<k&&k<=a[r])l=m+1;
else r=m-1
}
}
return dupes?false:-1
};

Execution canvas

Active Changed
STEP 1

Identify sorted half

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

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

Worked example and algorithm walkthrough

Topic: Binary Search · Sorted arrays

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": [
    4,
    5,
    6,
    7,
    0,
    1,
    2
  ],
  "k": 0,
  "dupes": false
}

Execution steps

  1. Identify sorted half

Computed output

4
JavaScript reference implementation
const solve = ({
  a,k,dupes
},s)=>{
  let l=0,r=a.length-1;
  while(l<=r){
    let m=(l+r)>>1;
    s("Identify sorted half",{
      Array:a,Bounds:[l,m,r]
    },[l,m,r]);
    if(a[m]===k)return dupes?true:m;
    if(a[l]===a[m]&&a[m]===a[r]){
      l++;
      r--
    }else if(a[l]<=a[m]){
      if(a[l]<=k&&k<a[m])r=m-1;
      else l=m+1
    }else{
      if(a[m]<k&&k<=a[r])l=m+1;
      else r=m-1
    }
  }
  return dupes?false:-1
};

Continue learning

Practice related DSA questions in the same topic.