readyforhires

Arrays & Strings 101

Fundamental · 4 chapters · 8 min read · Master the in-place tricks and index arithmetic behind most first-round questions.

Practise this in the app All guides

Why arrays and strings come first

The most common interview data structure

Almost every coding round in India, from campus placements to product-company loops, opens with an array or string question. They look simple, which is exactly why they are used: the interviewer wants to see whether you can handle indices, boundaries and in-place updates cleanly without a bug.

An array is a block of contiguous memory. Reading a[i] is O(1), but inserting or deleting in the middle is O(n) because every later element has to shift. A Python str is an immutable array of characters, so s[i] = 'x' is not allowed and s += c inside a loop may copy the whole string each time.

Signals in a problem statement

Reach for array techniques when you see:

Mental model

Treat indices as the real variables of the problem. Before writing code, write down what each index means ("write is the next free slot", "top is the first unfilled row"). Most array bugs come from an index whose meaning drifts halfway through the loop. When you can state that meaning in one sentence, the loop body almost writes itself.

Core patterns with templates

1. Reverse a range in place

Rotating right by k equals: reverse all, reverse the first k, reverse the rest.

def reverse(a, lo, hi):
    while lo < hi:
        a[lo], a[hi] = a[hi], a[lo]
        lo += 1
        hi -= 1

def rotate(a, k):
    n = len(a)
    k %= n
    reverse(a, 0, n - 1)
    reverse(a, 0, k - 1)
    reverse(a, k, n - 1)

Example: [1,2,3,4,5], k=2 → reversed [5,4,3,2,1] → [4,5,3,2,1] → [4,5,1,2,3].

2. Fill from the back when merging

def merge(a, m, b, n):
    i, j, w = m - 1, n - 1, m + n - 1
    while j >= 0:
        if i >= 0 and a[i] > b[j]:
            a[w] = a[i]
            i -= 1
        else:
            a[w] = b[j]
            j -= 1
        w -= 1

3. Boyer-Moore majority vote

def majority(a):
    cand, count = None, 0
    for x in a:
        if count == 0:
            cand = x
        count += 1 if x == cand else -1
    return cand

4. Build strings with a list

def reverse_words(s):
    return " ".join(reversed(s.split()))

split() with no argument drops leading, trailing and repeated spaces. When you must build character by character, append to a list and "".join(parts) once at the end.

5. Shrinking boundaries for a matrix walk

Keep top, bottom, left, right. Walk the top row, then top += 1; the right column, then right -= 1; and so on, checking top <= bottom and left <= right before the bottom row and left column so a single remaining row is not visited twice.

Complexity, mistakes and edge cases

Costs to remember

OperationPython listNote
a[i], a[i] = xO(1)
a.append(x), a.pop()O(1) amortisedend of list only
a.insert(0, x), a.pop(0)O(n)use collections.deque
x in aO(n)use a set for membership
a[l:r]O(r - l)slicing copies
"".join(parts)O(total length)preferred for building strings

Mistakes interviewers see daily

Edge cases to test aloud

Empty array, single element, all elements equal, already sorted, reverse sorted, negative numbers and zero, a matrix with one row or one column, strings with leading or trailing spaces, and very large k. Saying these before you code shows the interviewer you think like someone who ships production code.

Using the array as its own hash table

When values are known to lie in 1..n, you can place each value v at index v - 1 by swapping. After one pass, the first index i where a[i] != i + 1 gives the answer to "first missing positive". Every swap puts at least one value in its final home, so the total work is O(n) even though there is a while inside a for.

Variations and practise

How interviewers twist array questions

A habit that pays off

Before coding, say the approach and its complexity in one sentence: "I will reverse three ranges, O(n) time, O(1) space." Then code it, then dry-run on a tiny example of three to five elements. Interviewers in Indian product companies often score clarity of communication as heavily as correctness.

Practise

The problems below move from warm-up merges and votes to matrix walks and the in-place hashing trick. Solve the Easy ones without looking at hints, time yourself on the Medium ones (aim for 25 minutes), and treat the Hard ones as practice for explaining an idea step by step before you write any code.

Practise

Easy

Medium

Hard

Practise this in the app All guides