In-place Manipulation

Loading concept...

🎨 Array Mastery: The Art of In-Place Magic

The Big Picture

Imagine you have a messy toy box. Your mom says: “Clean it up, but you can’t use another box!” That’s in-place manipulation! You organize everything inside the same box, using clever swaps and moves.

In programming, in-place means we transform an array without creating a new one. We use O(1) extra space — just a few helper variables, no new arrays.

Today, we’ll master four magical techniques that real programmers use every day!


🏳️ The Dutch National Flag Algorithm

The Story

A little boy had a bag of red, white, and blue marbles — all mixed up! He wanted to sort them so all reds come first, then whites, then blues. But he could only use one bag and three fingers to point at positions.

How It Works

We use three pointers:

  • low → Where the next red (0) should go
  • mid → The marble we’re currently looking at
  • high → Where the next blue (2) should go
def dutch_flag_sort(arr):
    low = 0
    mid = 0
    high = len(arr) - 1

    while mid <= high:
        if arr[mid] == 0:  # Red!
            arr[low], arr[mid] = arr[mid], arr[low]
            low += 1
            mid += 1
        elif arr[mid] == 1:  # White!
            mid += 1
        else:  # Blue!
            arr[mid], arr[high] = arr[high], arr[mid]
            high -= 1

    return arr

Example Walk-Through

Start: [2, 0, 1, 2, 0, 1]
       low=0, mid=0, high=5

Step 1: arr[mid]=2 → swap with high
        [1, 0, 1, 2, 0, 2], high=4

Step 2: arr[mid]=1 → just move mid
        mid=1

Step 3: arr[mid]=0 → swap with low
        [0, 1, 1, 2, 0, 2], low=1, mid=2

...continue until done!

Final: [0, 0, 1, 1, 2, 2] ✨

Why It’s Magic

  • One pass through the array (O(n) time)
  • No extra array (O(1) space)
  • Each element moves to its final place!

🗳️ The Boyer-Moore Voting Algorithm

The Story

Imagine a classroom election. Everyone shouts their vote at once! It’s chaos. But there’s a clever trick: if someone shouts “Maya!” and another shouts “Tom!”, their votes cancel out. After all the canceling, whoever’s voice remains is the winner (majority)!

The Magic Rule

If you see the same name → count goes UP (+1)
If you see different name → count goes DOWN (-1)
When count hits 0 → pick a new candidate!

Python Code

def find_majority(nums):
    candidate = None
    count = 0

    for num in nums:
        if count == 0:
            candidate = num
            count = 1
        elif num == candidate:
            count += 1
        else:
            count -= 1

    return candidate

Example Walk-Through

Array: [2, 2, 1, 1, 2, 2, 1]

Step 1: count=0, pick 2 → candidate=2, count=1
Step 2: see 2 → count=2
Step 3: see 1 → count=1
Step 4: see 1 → count=0
Step 5: count=0, pick 2 → candidate=2, count=1
Step 6: see 2 → count=2
Step 7: see 1 → count=1

Result: candidate=2 ✓ (appears 4 times out of 7)

Why It Works

Think of it as a battle:

  • Every majority soldier is stronger because there are more of them
  • Even if every minority soldier cancels one majority soldier, the majority still has soldiers left!

Time: O(n) — one pass Space: O(1) — just two variables!


🗑️ Remove Duplicates from Sorted Array

The Story

You have a line of kids sorted by height. Some kids are twins (same height, standing next to each other). The teacher says: “I only want one kid of each height at the front. Don’t send anyone home — just move unique kids to the front!”

The Two-Pointer Trick

def remove_duplicates(nums):
    if not nums:
        return 0

    # slow = where to put next unique
    slow = 0

    for fast in range(1, len(nums)):
        if nums[fast] != nums[slow]:
            slow += 1
            nums[slow] = nums[fast]

    return slow + 1  # length of unique part

Example Walk-Through

Start: [1, 1, 2, 2, 2, 3]
       slow=0

fast=1: nums[1]=1 == nums[0]=1 → skip

fast=2: nums[2]=2 != nums[0]=1
        slow=1, nums[1]=2
        Array: [1, 2, 2, 2, 2, 3]

fast=3: nums[3]=2 == nums[1]=2 → skip
fast=4: nums[4]=2 == nums[1]=2 → skip

fast=5: nums[5]=3 != nums[1]=2
        slow=2, nums[2]=3
        Array: [1, 2, 3, 2, 2, 3]

Return: 3 (first 3 elements are unique)
Unique part: [1, 2, 3]

The Key Insight

  • slow marks the end of the “clean” unique zone
  • fast explores ahead, finding new unique values
  • When fast finds something new, we add it to the clean zone!

🏃 Move Zeroes

The Story

Picture a race! The runners (non-zero numbers) should be at the front, and lazy sleepers (zeros) should be pushed to the back. But everyone must stay in their original order — no one can cut in line!

The Snowplow Technique

Imagine a snowplow pushing all the snow (zeros) to the end of the street:

def move_zeroes(nums):
    # insert_pos = where to put next runner
    insert_pos = 0

    # First pass: bring all runners forward
    for num in nums:
        if num != 0:
            nums[insert_pos] = num
            insert_pos += 1

    # Second pass: fill the rest with zeros
    while insert_pos < len(nums):
        nums[insert_pos] = 0
        insert_pos += 1

One-Pass Version (Swap Trick)

def move_zeroes_swap(nums):
    slow = 0  # boundary of non-zero zone

    for fast in range(len(nums)):
        if nums[fast] != 0:
            nums[slow], nums[fast] = nums[fast], nums[slow]
            slow += 1

Example Walk-Through

Start: [0, 1, 0, 3, 12]
       slow=0

fast=0: nums[0]=0 → skip

fast=1: nums[1]=1 != 0
        swap: [1, 0, 0, 3, 12], slow=1

fast=2: nums[2]=0 → skip

fast=3: nums[3]=3 != 0
        swap: [1, 3, 0, 0, 12], slow=2

fast=4: nums[4]=12 != 0
        swap: [1, 3, 12, 0, 0], slow=3

Final: [1, 3, 12, 0, 0] ✨

Why Order is Preserved

Each non-zero element moves forward one at a time, in the exact order they appeared. It’s like a conveyor belt!


🧠 The Big Pattern

All four algorithms share the same secret:

graph TD A[Use Two Pointers] --> B[One Slow Pointer] A --> C[One Fast Pointer] B --> D[Marks Boundary] C --> E[Explores Ahead] D --> F[Swap or Write] E --> F F --> G[O#40;n#41; Time, O#40;1#41; Space!]

The Family

Algorithm What It Does Pointers Used
Dutch Flag Sort 3 colors low, mid, high
Boyer-Moore Find majority candidate, count
Remove Duplicates Keep unique slow, fast
Move Zeroes Push zeros back slow, fast

🎯 When to Use What?

Dutch National Flag:

“I have exactly 3 categories to sort”

Boyer-Moore:

“I need to find the element appearing more than half the time”

Remove Duplicates:

“Array is sorted, I want unique elements first”

Move Zeroes:

“Push certain values to the end, keep order for others”


🚀 You’re Now an In-Place Master!

You’ve learned the art of transforming arrays without extra space:

  1. Dutch Flag — Three-way partition with three pointers
  2. Boyer-Moore — Voting/cancellation to find majority
  3. Remove Duplicates — Two pointers in sorted arrays
  4. Move Zeroes — Snowplow technique

The secret? Most in-place problems are solved with two pointers doing a careful dance:

  • One pointer holds the boundary of the “good” zone
  • Another pointer explores to find what goes there

Now go practice, and watch arrays transform before your eyes! 🎨✨

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.