LC-TEST-21 — Algorithm Test (V5)

🪄 Why This Exists

Top companies do not only test coding.

They test:

  • Logical reasoning
  • Mathematical intuition
  • Pattern recognition
  • Constraint thinking
  • How you explain ideas simply

This chapter trains your brain, not just Python syntax.

🎭 Theme: Harry Potter × Disney Because great engineers still know how to have fun.


🧩 Wizard & Cartoon Logic (20 Puzzles)


🟢 Problem 1 — Harry’s Spell Counter

Harry casts spells with power values:

spells = [3, 5, 2, 7]

Task: Calculate total spell power without using sum()

✅ Solution — Pure Logic
total = 0
for s in spells:
    total += s
print(total)

Time: O(n) Space: O(1)


🟢 Problem 2 — Sorting Hat Decision

Students’ bravery scores:

bravery = [7, 8, 6, 9]

Gryffindor accepts only if all scores ≥ 7

✅ Solution — Early Exit
ok = True
for b in bravery:
    if b < 7:
        ok = False
        break
print(ok)

🟢 Problem 3 — Mickey’s Unique Balloons 🎈

balloons = ["red","blue","red","yellow"]

How many unique colors?

✅ Solution — NO LIB
seen = {}
count = 0
for b in balloons:
    if b not in seen:
        seen[b] = True
        count += 1
print(count)

🟡 Problem 4 — First Repeated Spell (Dark Magic)

spells = ["Lumos","Accio","Expelliarmus","Accio"]
✅ Solution — Hash Memory
seen = set()
for s in spells:
    if s in seen:
        print(s)
        break
    seen.add(s)

🟡 Problem 5 — Elsa’s Ice Power Window ❄️

Ice power per minute:

power = [30, 60, 80, 20, 40]

Alert if any 3 consecutive minutes > 150

✅ Solution — Sliding Window (Pure)
window = power[0] + power[1] + power[2]

for i in range(3, len(power)):
    if window > 150:
        print(True)
        break
    window += power[i] - power[i-3]
else:
    print(window > 150)

🟡 Problem 6 — Hogwarts Staircases (Steps Puzzle)

A wizard climbs n steps. Can move 1 or 2 steps.

Task: Ways to reach step n = 5

✅ Solution — DP (Pure)
n = 5
a, b = 1, 1
for _ in range(n):
    a, b = b, a + b
print(a)

Time: O(n) Space: O(1)


🟡 Problem 7 — Simba’s Territory Peaks 🦁

land = [1, 3, 2, 4, 1]

Count peaks (greater than neighbors)

✅ Solution — Manual Scan
count = 0
for i in range(1, len(land)-1):
    if land[i] > land[i-1] and land[i] > land[i+1]:
        count += 1
print(count)

🟡 Problem 8 — Olaf’s Snowball Balance ☃️

Snowballs weights:

balls = [1,2,3,6]

Can split into two equal-sum groups?

✅ Solution — Prefix Logic
total = 0
for b in balls:
    total += b

left = 0
possible = False
for b in balls:
    left += b
    if left * 2 == total:
        possible = True
        break

print(possible)

🔵 Problem 9 — Hermione’s Prime Spell 🔢

Is n = 29 prime?

✅ Solution — Pure Math
n = 29
prime = n > 1

i = 2
while i * i <= n:
    if n % i == 0:
        prime = False
        break
    i += 1

print(prime)

🔵 Problem 10 — Buzz Lightyear Range 🚀

nums = [1, 4, 7, 10]

Find max distance between adjacent numbers

✅ Solution
best = 0
for i in range(1, len(nums)):
    best = max(best, nums[i] - nums[i-1])
print(best)

🔵 Problem 11 — Aladdin’s Magic Carpet Turns

path = "LLRRLR"

Start at 0. Left = −1, Right = +1 Did Aladdin return to start?

✅ Solution — Counter
pos = 0
for p in path:
    pos += -1 if p == "L" else 1
print(pos == 0)

🔵 Problem 12 — Moana’s Island Jump 🌊

stones = [2,3,1,1,4]

Each number = max jump length. Can reach last stone?

✅ Solution — Greedy
reach = 0
for i, s in enumerate(stones):
    if i > reach:
        print(False)
        break
    reach = max(reach, i + s)
else:
    print(True)

🔴 Problem 13 — Darth Vader Balance (Force Split)

force = [1,5,11,5]

Split into equal sum?

✅ Solution — Subset Sum (DP)
total = sum(force)
if total % 2 != 0:
    print(False)
else:
    target = total // 2
    dp = {0}
    for f in force:
        dp |= {x + f for x in dp}
    print(target in dp)

🔴 Problem 14 — Hogwarts Class Scheduler

Classes durations:

classes = [30, 15, 60, 45]

Fit into 90 minutes max?

✅ Solution — Greedy Sort
classes.sort()
time = 0

for c in classes:
    time += c
    if time > 90:
        print(False)
        break
else:
    print(True)

🔴 Problem 15 — Peter Pan’s Lost Numbers

nums = [1, 2, 4, 5]

There is one missing number from the range 1..n. Can you find it?


✅ Solution 1 — Math Trick (Sum Formula)

💡 Idea

If numbers from 1..n were complete, their sum would be:

$$ \frac{n(n+1)}{2} $$

Since one number is missing, subtract the actual sum from the expected sum.

🧠 Why it works

The difference between the two sums is exactly the missing number.

nums = [1, 2, 4, 5]

n = len(nums) + 1
expected = n * (n + 1) // 2
actual = sum(nums)

print(expected - actual)

⏱ Time: O(n) 📦 Space: O(1)


✅ Solution 2 — Using XOR (Beginner Friendly)

💡 Idea (Plain English)

XOR (^) checks whether two values are the same or different.

  • Same → 0
  • Different → 1

You only need to remember these two rules:

a ^ a = 0   # same values cancel out
a ^ 0 = a   # XOR with 0 keeps the value

🧠 Why it works (Step by Step)

We XOR together:

  • all numbers from 1..n
  • all numbers in the array

What happens?

  • Numbers that exist in the array appear twice → they cancel out (a ^ a = 0)
  • The missing number appears only once → it does NOT cancel out and remains

That remaining value is the missing number.


🔍 Simple Example

1 ^ 1 = 0
2 ^ 2 = 0
4 ^ 4 = 0
5 ^ 5 = 0

The number 3 has no pair, so it survives.


🧪 Code

nums = [1, 2, 4, 5]

n = len(nums) + 1
xor_all = 0

for i in range(1, n + 1):
    xor_all ^= i

for x in nums:
    xor_all ^= x

print(xor_all)

⏱ Time: O(n) 📦 Space: O(1) 😎 Bonus: No math formula required


✅ Solution 3 — Hash Set (Most Intuitive)

💡 Idea

Store all numbers in a set, then scan from 1..n to find what’s missing.

🧠 Why it works

Set lookup is O(1), making the solution simple and readable.

nums = [1, 2, 4, 5]

num_set = set(nums)
n = len(nums) + 1

for i in range(1, n + 1):
    if i not in num_set:
        print(i)
        break

⏱ Time: O(n) 📦 Space: O(n) 👍 Best for beginners / clarity


⚠️ Solution 4 — Using max() (⚠️ Not Always Safe)

💡 Idea

Assume the largest number in the array is n, then apply the sum formula.

nums = [1, 2, 4, 5]

n = max(nums)
expected = n * (n + 1) // 2
actual = sum(nums)

print(expected - actual)

❌ Why this can fail

This approach assumes the missing number is NOT n.

Example where it breaks:

nums = [1, 2, 3, 4]  # missing 5
  • max(nums) = 4
  • Expected sum = 1 + 2 + 3 + 4 = 10
  • Actual sum = 10
  • Result = 0 ❌ (wrong)

✅ When it works

  • Numbers start from 1
  • Missing number is not the last one
  • Array is guaranteed to contain n

📌 Verdict

This solution is clever but dangerous Use only if the problem explicitly guarantees that n exists in the array.


🧩 Final Thoughts

Solution Time Space Best Use Case
Math Trick O(n) O(1) Interviews, clean code
XOR O(n) O(1) Bitwise lovers 😎
Hash Set O(n) O(n) Readability & teaching
max() O(n) O(1) ⚠️ Risky

Recommended: Use Math Trick for interviews, Hash Set for clarity, XOR to impress hardcore engineers.


🔴 Problem 16 — Toy Story Pair Sum 🧸

nums = [2,7,11,15]
target = 9
✅ Solution — Hash
seen = {}
for i, n in enumerate(nums):
    if target - n in seen:
        print(seen[target - n], i)
        break
    seen[n] = i

🔴 Problem 17 — Wizard’s Mirror Palindrome

s = "racecar"
✅ Solution — Two Pointers
l, r = 0, len(s)-1
ok = True

while l < r:
    if s[l] != s[r]:
        ok = False
        break
    l += 1
    r -= 1

print(ok)

🔴 Problem 18 — Cinderella’s Time Loop ⏰

times = [1,2,3,4,5]

Rotate right by 2 without slicing

✅ Solution — Manual Rotate
k = 2
for _ in range(k):
    last = times[-1]
    i = len(times) - 1
    while i > 0:
        times[i] = times[i-1]
        i -= 1
    times[0] = last

print(times)

🔴 Problem 19 — Thanos Balance Check ⚖️

nums = [3,3,3,3]

All values equal?

✅ Solution
same = True
for i in range(1, len(nums)):
    if nums[i] != nums[0]:
        same = False
        break
print(same)

🔴 Problem 20 — Avengers Final Merge 🛡️

a = [1,3,5]
b = [2,4,6]

Merge sorted arrays (again, no sort())

✅ Solution — Two Pointers
i = j = 0
res = []

while i < len(a) and j < len(b):
    if a[i] < b[j]:
        res.append(a[i]); i += 1
    else:
        res.append(b[j]); j += 1

res += a[i:] + b[j:]
print(res)

🏁 Final Words

If you can:

  • Solve these
  • Explain why
  • Smile while doing it 😄

Then you are:

  • 🧠 Logically strong
  • 💼 Interview ready
  • ❤️ Still human

Great engineers can reason. Legendary engineers can make it fun.


Previous
Next