Bird
Raised Fist0
DSA Typescriptprogramming~10 mins

Binary Search vs Linear Search Real Cost Difference in DSA Typescript - Visual Comparison

Choose your learning style10 modes available
Concept Flow - Binary Search vs Linear Search Real Cost Difference
Start Search
↓
Choose Search Type
↓
Linear
↓
Check each
↓
Found?
No→Adjust range
↓
Return
Yes↓
Return
↓
Adjust range
↓
Repeat
↓
Not Found
↓
Return
Shows the choice between linear and binary search and their step-by-step decision process.
Execution Sample
DSA Typescript
function linearSearch(arr: number[], target: number): number {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) return i;
  }
  return -1;
}

function binarySearch(arr: number[], target: number): number {
  let left = 0, right = arr.length - 1;
  while (left <= right) {
    let mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) return mid;
    else if (arr[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return -1;
}
Linear search checks each element one by one; binary search divides the search range in half each step.
Execution Table
StepOperationIndex CheckedComparison ResultPointer ChangesVisual State
1Linear Search StartNoneN/Ai=0[5, 8, 12, 20, 25]
2Check arr[0]05 == 20? Noi=1[5, 8, 12, 20, 25]
3Check arr[1]18 == 20? Noi=2[5, 8, 12, 20, 25]
4Check arr[2]212 == 20? Noi=3[5, 8, 12, 20, 25]
5Check arr[3]320 == 20? YesFound at 3[5, 8, 12, 20, 25]
6Linear Search End3Found targetReturn 3[5, 8, 12, 20, 25]
7Binary Search StartNoneN/Aleft=0, right=4[5, 8, 12, 20, 25]
8Calculate mid2arr[2]=12mid=2[5, 8, 12, 20, 25]
9Compare arr[2]212 == 20? Noleft=3, right=4[5, 8, 12, 20, 25]
10Adjust left3left=3left=3, right=4[5, 8, 12, 20, 25]
11Calculate mid3arr[3]=20mid=3[5, 8, 12, 20, 25]
12Compare arr[3]320 == 20? YesFound at 3[5, 8, 12, 20, 25]
13Binary Search End3Found targetReturn 3[5, 8, 12, 20, 25]
14Linear Search Worst Case425 == 30? Noi=5[5, 8, 12, 20, 25]
15Linear Search EndNoneTarget not foundReturn -1[5, 8, 12, 20, 25]
16Binary Search Worst Case StartNoneN/Aleft=0, right=4[5, 8, 12, 20, 25]
17Calculate mid2arr[2]=12mid=2[5, 8, 12, 20, 25]
18Compare arr[2]212 == 30? Noleft=3, right=4[5, 8, 12, 20, 25]
19Calculate mid3arr[3]=20mid=3[5, 8, 12, 20, 25]
20Compare arr[3]320 == 30? Noleft=4, right=4[5, 8, 12, 20, 25]
21Calculate mid4arr[4]=25mid=4[5, 8, 12, 20, 25]
22Compare arr[4]425 == 30? Noleft=4, right=3[5, 8, 12, 20, 25]
23Binary Search EndNoneTarget not foundReturn -1[5, 8, 12, 20, 25]
💡 Search ends when target is found or search range is empty (left > right).
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 5After Step 7After Step 10After Step 11After Step 14After Step 18After Step 21Final
i (Linear Search)0133 (found)N/AN/AN/A5 (end)N/AN/AN/A
left (Binary Search)N/AN/AN/AN/A0330344
right (Binary Search)N/AN/AN/AN/A4444443
mid (Binary Search)N/AN/AN/AN/A223234N/A
Key Moments - 3 Insights
Why does binary search adjust 'left' or 'right' pointers instead of checking every element?
Binary search divides the search range in half each time by adjusting 'left' or 'right' pointers, reducing the number of checks needed. This is shown in steps 9, 10, 18, and 22 where pointers move instead of checking all elements.
Why does linear search sometimes take more steps than binary search?
Linear search checks each element one by one until it finds the target or reaches the end, as seen in steps 2 to 5 and 14. Binary search quickly narrows down the search range, so it usually takes fewer steps, shown in steps 7 to 13.
What happens when the target is not in the array?
Both searches return -1 when the target is not found. Linear search ends after checking all elements (step 15), binary search ends when 'left' pointer passes 'right' (step 23).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'mid' at step 11 during binary search?
A3
B2
C4
D1
💡 Hint
Check the 'mid (Binary Search)' row in variable_tracker after step 11.
At which step does linear search find the target 20?
AStep 3
BStep 5
CStep 6
DStep 4
💡 Hint
Look at the 'Comparison Result' column in execution_table for linear search steps.
If the target was the first element (5), how would linear search's 'i' variable change in the execution table?
AIt would return at i=0
BIt would check all elements
CIt would return at i=1
DIt would never find the target
💡 Hint
Linear search returns immediately when it finds the target, as shown in steps 2-5.
Concept Snapshot
Binary Search vs Linear Search:
- Linear Search checks each element one by one.
- Binary Search divides search range in half each step.
- Binary Search requires sorted array.
- Linear Search works on any array.
- Binary Search is faster for large sorted arrays.
- Linear Search is simple but slower for big data.
Full Transcript
This visual compares linear and binary search methods. Linear search checks each element from start to end until it finds the target or finishes the list. Binary search works only on sorted arrays and repeatedly checks the middle element, adjusting the search range by moving left or right pointers. The execution table shows step-by-step how each search checks elements and updates pointers. Variable tracker shows how indexes and pointers change. Key moments clarify why binary search adjusts pointers instead of checking all elements, why linear search can take more steps, and what happens when the target is not found. The quiz tests understanding of mid calculation, step when target is found, and behavior if target is first element. The snapshot summarizes the main differences and use cases.

Practice

(1/5)
1. Which search algorithm is generally faster on a sorted list of 1,000,000 elements?
easy
A. Linear Search
B. Both are equally fast
C. Binary Search
D. Neither works on sorted lists

Solution

  1. Step 1: Understand the search algorithms

    Binary Search divides the list in half repeatedly, while Linear Search checks each element one by one.
  2. Step 2: Compare efficiency on large sorted lists

    Binary Search takes about log2(1,000,000) ≈ 20 steps, Linear Search takes up to 1,000,000 steps.
  3. Final Answer:

    Binary Search -> Option C
  4. Quick Check:

    Binary Search is faster on sorted lists [OK]
Hint: Binary Search halves search space; Linear checks all [OK]
Common Mistakes:
  • Thinking Linear Search is faster on sorted lists
  • Confusing sorted and unsorted list requirements
  • Ignoring the difference in step counts
2. Which of the following is the correct TypeScript syntax to perform a linear search on an array arr for a value target?
easy
A. arr.findIndex(target);
B. for (let i = 0; i < arr.length; i++) { if (arr[i] === target) return i; }
C. while (arr.includes(target)) { return arr.indexOf(target); }
D. for (let i in arr) { if (arr[i] == target) return i; }

Solution

  1. Step 1: Check syntax for linear search loop

    for (let i = 0; i < arr.length; i++) { if (arr[i] === target) return i; } uses a for loop with index and compares each element to target correctly.
  2. Step 2: Analyze other options for correctness

    while (arr.includes(target)) { return arr.indexOf(target); } misuses while with includes; arr.findIndex(target); uses findIndex incorrectly; for (let i in arr) { if (arr[i] == target) return i; } uses 'in' which iterates keys but with loose equality.
  3. Final Answer:

    for (let i = 0; i < arr.length; i++) { if (arr[i] === target) return i; } -> Option B
  4. Quick Check:

    Correct for loop syntax for linear search [OK]
Hint: Use for loop with strict equality for linear search [OK]
Common Mistakes:
  • Using while loop incorrectly
  • Using loose equality (==) instead of strict (===)
  • Misusing array methods for search
3. What will be the output of the following TypeScript code snippet?
const arr = [1, 3, 5, 7, 9];
function binarySearch(array: number[], target: number): number {
  let left = 0;
  let right = array.length - 1;
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (array[mid] === target) return mid;
    else if (array[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return -1;
}
console.log(binarySearch(arr, 7));
medium
A. 3
B. 2
C. -1
D. 4

Solution

  1. Step 1: Trace binary search steps for target 7

    Initial left=0, right=4, mid=2 (value 5). 5 < 7, so left=3.
  2. Step 2: Next iteration mid=3 (value 7), matches target, return 3

    The function returns index 3 where 7 is found.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Index of 7 in array is 3 [OK]
Hint: Calculate mid index and compare stepwise [OK]
Common Mistakes:
  • Confusing mid calculation
  • Returning wrong index
  • Not updating left/right correctly
4. Identify the bug in this linear search function and select the fix:
function linearSearch(arr: number[], target: number): number {
  for (let i = 0; i <= arr.length; i++) {
    if (arr[i] === target) return i;
  }
  return -1;
}
medium
A. Change loop condition to i < arr.length
B. Change === to == in if condition
C. Add a break after return statement
D. Initialize i to 1 instead of 0

Solution

  1. Step 1: Analyze loop condition

    The loop runs while i <= arr.length, which causes out-of-bounds access at i = arr.length.
  2. Step 2: Fix loop condition to prevent error

    Changing to i < arr.length ensures valid indices only.
  3. Final Answer:

    Change loop condition to i < arr.length -> Option A
  4. Quick Check:

    Loop must stay within array bounds [OK]
Hint: Use i < arr.length to avoid out-of-bounds [OK]
Common Mistakes:
  • Using <= instead of < in loop
  • Changing equality operator unnecessarily
  • Adding break after return (unreachable code)
5. You have a sorted array of 10,000 elements and want to find a target value. Which approach minimizes the average number of comparisons, and why?

Options:
A) Use Linear Search because it checks elements sequentially.
B) Use Linear Search but start from the middle.
C) Use Binary Search but only check every other element.
D) Use Binary Search because it divides the search space each step.
hard
A. Use Linear Search because it checks elements sequentially.
B. Use Linear Search but start from the middle.
C. Use Binary Search but only check every other element.
D. Use Binary Search because it divides the search space each step.

Solution

  1. Step 1: Understand average comparisons for Linear vs Binary Search

    Linear Search averages about n/2 = 5,000 comparisons; Binary Search averages about log2(10,000) ≈ 14 comparisons.
  2. Step 2: Evaluate options for efficiency

    Binary Search halves search space each step, minimizing comparisons. Starting Linear Search from middle or skipping elements breaks correctness or efficiency.
  3. Final Answer:

    Use Binary Search because it divides the search space each step. -> Option D
  4. Quick Check:

    Binary Search minimizes comparisons on sorted arrays [OK]
Hint: Binary Search halves search space, fewer comparisons [OK]
Common Mistakes:
  • Thinking linear search is faster on sorted arrays
  • Starting linear search from middle doesn't help
  • Skipping elements in binary search breaks correctness
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard