Data structures and Algorithms

Designing efficient solutions through structured thinking, optimization techniques, and advanced programming logic.

Published on 13 feb 2026

Data structures and Algorithms

1. Two Sum

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to the target.

Rules

  • each input has exactly one solution
  • you cannot use the same element twice
  • return the answer in any order

Examples

Example 1: Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9

Example 2: Input: nums = [3, 2, 4], target = 6
Output: [1, 2]
Explanation: 2 + 4 = 6

Example 3: Input: nums = [3, 3], target = 6
Output: [0, 1]

Test Cases

  1. nums = [2,7,11,15], target = 9[0,1]
  2. nums = [3,2,4], target = 6[1,2]
  3. nums = [3,3], target = 6[0,1]
  4. nums = [1,5,3,7], target = 8[0,3] or [1,2]
  5. nums = [-1,-2,-3,-4,-5], target = -8[2,4]
2SUM
Solution · JS
Array · i= target=9
20
71
112
153
current lookup appears here
MAP{ }
Index
Num
Need
Map
0
Found
0 / 0
Execution log
steps appear here…

2. Find the length of the longest substring without repeating characters ?

SW
Solution · JS
Window · L=  R=
a0
b1
c2
a3
b4
c5
b6
b7
MAP{ }
Left
Right
Win
0
Best
0
Step
0 / 0
Execution log
steps appear here…

3. Remove Duplicates from Sorted Array

Given a sorted array nums, remove duplicates in-place so each element appears only once.

Return the number of unique elements k.

The first k elements of the array should contain the unique values in the same order.

Rules

  • do not create a new array
  • use O(1) extra space
  • keep the original order

Examples

Example 1: Input: nums = [1,1,2]
Output: k = 2, nums = [1,2,_]
Explanation: first 2 elements are unique

Example 2: Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: k = 5, nums = [0,1,2,3,4,_,_,_,_,_]

Test Cases

  1. [1,1,2] → k = 2
  2. [0,0,1,1,1,2,2,3,3,4] → k = 5
  3. [1,2,3] → k = 3
  4. [1,1,1,1] → k = 1
  5. [] → k = 0
  6. [-1,-1,0,0,1] → k = 3

Hint

Use two pointers:

  • one pointer tracks where the next unique value should go
  • one pointer scans the array

Think like:

if current != previous unique, keep it

REMOVE DUPES
Solution · JS
Array · read= write=0
10
11
22
current
prev unique
k 0
unique prefix appears here
Read
Write
0
Current
Prev
k
0
0 / 0
Execution log
steps appear here…

4. Write a function to calculate the square root of a number without using Math.sqrt(). The result should be accurate up to 2 decimal places.

Live Editor

Loading...

Output

Run code to see output...

Explanation of Your Logic

Your method works like this:

Step 1 — Start With a Guess

You begin with currentGuess.

Step 2 — Compare Square With Target

You check:

currentGuess² vs number

There are 3 cases:

  1. If square is smaller → guess is too small → increase it
  2. If square is bigger → guess is too big → decrease it
  3. If difference < 0.1 → stop
Step 3 — Gradually Reduce Step Size

You adjust guess using:

currentGuess ± (currentGuess / stepFactor)

Since stepFactor increases each recursion:

Adjustment gets smaller

Guess becomes more precise over time

5. 3Sum

Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that:

nums[i] + nums[j] + nums[k] === 0

Rules

  1. Triplets must be unique (no duplicates)
  2. Order inside triplet doesn’t matter
  3. Order of result doesn’t matter
3SUM
Solution · JS
Array · i= L= R=
-10
01
12
23
-14
-45
sum will appear here
RESULT[ ]
i
L
R
Sum
Found
0
0 / 0
Execution log
steps appear here…

6. Best Time to Buy and Sell Stock

You are given an array prices where:

prices[i] = price of stock on day i

You want to maximize profit by:

  • choosing one day to buy
  • choosing one later day to sell

Rules

  1. You must buy before you sell
  2. Only one transaction allowed
  3. If no profit is possible, return 0

Examples Example 1

  • Input: prices = [7,1,5,3,6,4]
  • Output: 5
  • Explanation: Buy at 1 and sell at 6

Example 2

  • Input: prices = [7,6,4,3,1]
  • Output: 0
  • Explanation: No profit is possible

Test Cases

  1. [7,1,5,3,6,4] → 5
  2. [7,6,4,3,1] → 0
  3. [1,2,3,4,5] → 4
  4. [5] → 0
  5. [2,4,1] → 2
  6. [3,2,6,5,0,3] → 4

Hint

Track:

  • the minimum price seen so far
  • the profit if you sell today

Think like:

If I sell today, what is my best buy so far?

STOCK
Solution · JS
Prices · day= min=
70
11
52
33
64
45
profit check appears here
BESTno profitable trade yet
Day
Min
Profit
Best
0
Trade
0 / 0
Execution log
steps appear here…

7. Valid Parentheses

Given a string s containing only:

( ) { } [ ]

Determine whether the string is valid.

A string is valid if

  1. open brackets are closed by the same type
  2. open brackets are closed in the correct order
  3. every closing bracket has a matching opening bracket

Examples

Example 1: Input: s = "()"
Output: true

Example 2: Input: s = "()[]{}"
Output: true

Example 3: Input: s = "(]"
Output: false
Explanation: ( is opened but closed with ]

Example 4: Input: s = "([)]"
Output: false
Explanation: order is wrong

Example 5: Input: s = "{[]}"
Output: true

Test Cases

  1. "()" → true
  2. "()[]{}" → true
  3. "(]" → false
  4. "([)]" → false
  5. "{[]}" → true
  6. "" → true
  7. "[" → false
  8. "]" → false
  9. "((()))" → true
  10. "((())" → false

Hint

Think about stack (LIFO):

  • push opening brackets
  • when you see a closing bracket, compare with the top of the stack
STACK
Solution · JS
String · i= ch=
(0
)1
STACK[ ]
matching info appears here
Index
Char
Stack
0
Need
Valid
0 / 0
Execution log
steps appear here…

8. Trapping Rain Water

At each index:

water = min(leftMax, rightMax) - height[i]

Because trapped water is always limited by the shorter boundary.

Best Approach: Two Pointers

Instead of building separate leftMax and rightMax arrays, compute both on the fly using two pointers.

Step-by-Step Intuition

Example:

[0,1,0,2]

IndexHeightLeftMaxRightMaxWater
00020
11120
20121

Total trapped water = 1

Why This Works

The key condition is:

if (height[left] < height[right])

That means the left side is the limiting boundary, so it is safe to calculate water using leftMax.

Complexity

MetricValue
TimeO(n)
SpaceO(1)

Brute Force

For each index:

  • find maximum wall on the left
  • find maximum wall on the right
  • take the minimum of both

Time complexity becomes O(n²), which is too slow for interviews.

RAIN
Solution · JS
Bars · L= R=
0
0
1
1
0
2
2
3
1
4
0
5
1
6
3
7
2
8
1
9
2
10
1
11
leftMax 0
rightMax 0
added 0
water 0
Left
Right
LMax
0
RMax
0
Water
0
0 / 0
Execution log
steps appear here…

9. Longest Consecutive Sequence

Given an unsorted array nums, return the length of the longest consecutive elements sequence.

Rules

  • sequence must be consecutive numbers
  • order in the array does not matter
  • solve it in O(n) time

Examples

Example 1: Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: sequence = [1,2,3,4]

Example 2: Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Example 3: Input: nums = []
Output: 0

Test Cases

  1. [100,4,200,1,3,2] → 4
  2. [0,3,7,2,5,8,4,6,0,1] → 9
  3. [] → 0
  4. [1,2,0,1] → 3
  5. [9,1,-3,2,4,8,3,-1,6,-2,-4,7] → 4

Hint

Use a Set.

Only start counting when:

num - 1 is not in the set

That means the number is the start of a sequence.

Think like:

  • avoid re-counting the same sequence
  • only expand forward
LONGEST SEQ
Solution · JS
Set · num= best=0
Nums
1000
41
2002
13
34
25
Set
100
4
200
1
3
2
length 0
best 0
current
current streak appears here
Num
Current
Length
0
Best
0
Set
6
0 / 0
Execution log
steps appear here…

10. LRU Cache

Design a data structure that follows the Least Recently Used policy.

Implement:

class LRUCache { constructor(capacity) {} get(key) {} put(key, value) {} }

Behavior

get(key)

  • return the value if the key exists
  • otherwise return -1
  • mark the key as recently used

put(key, value)

  • insert or update the value
  • if capacity is exceeded, remove the least recently used item

Example

LRUCache cache = new LRUCache(2)

  • cache.put(1, 1)
  • cache.put(2, 2)
  • cache.get(1) → 1
  • cache.put(3, 3) evicts key 2
  • cache.get(2) → -1
  • cache.put(4, 4) evicts key 1
  • cache.get(1) → -1
  • cache.get(3) → 3
  • cache.get(4) → 4

Interview Expectation

All operations must be O(1).

Hint

Use:

  • HashMap for O(1) access
  • Doubly Linked List for O(1) insert and remove

Key idea:

  • most recent item moves to the front
  • least recent item is removed from the end

Common Mistakes

  • using an array and getting O(n)
  • forgetting to update order on get
  • not evicting correctly when capacity is full
LRU CACHE`get` moves a key to MRU because it becomes recently used.
Operations
1.put(1, 1)
2.put(2, 2)
3.get(1)
4.put(3, 3)
5.get(2)
6.put(4, 4)
7.get(1)
8.get(3)
9.get(4)
Solution · JS
Doubly linked list · MRU → LRU
Doubly linked list
HEAD
TAIL
op
size 0/2
return
MAPempty
Cap
2
Size
0
Key
Return
0 / 0
Execution log
steps appear here…