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:
- "in-place" or "O(1) extra space" — you will overwrite the input as you go.
- "rotate", "reverse", "shift" — think of the reversal trick.
- "matrix", "grid", "spiral", "diagonal" — careful index arithmetic with four boundaries.
- "merge" two sorted arrays — fill from the back so nothing gets overwritten.
- "majority", "appears more than n/2 times" — a counting vote beats sorting.
- "first missing positive" with O(n) time and O(1) space — use the array itself as a hash table.
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
| Operation | Python list | Note |
|---|---|---|
a[i], a[i] = x | O(1) | |
a.append(x), a.pop() | O(1) amortised | end of list only |
a.insert(0, x), a.pop(0) | O(n) | use collections.deque |
x in a | O(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
- Off-by-one on ranges. Decide whether your bounds are inclusive or half-open and stick to it. Python's
range(lo, hi)is half-open. - Forgetting
k %= n. Rotating by aklarger than the length must wrap. - Modifying a list while iterating over it. Use a separate write index instead.
- Quadratic string building.
s = s + cin a loop can turn an O(n) solution into O(n²). - Hidden extra space.
a[::-1]andsorted(a)allocate new lists; say so if the question asks for O(1) space. - Mutating the input when it was not allowed. Ask first.
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
- Space constraint added later. You solve it with a set, then hear "now do it in O(1) space". Look for sorting, in-place marking (negate
a[v-1]), or a vote-style counter. - Greedy scan with running state. "Is there an increasing triplet?" can be solved by keeping the smallest and second-smallest values seen so far, updating them in one pass.
- Placement with neighbours. "Can you plant flowers without adjacent ones?" — scan once, treat out-of-range neighbours as empty, and place greedily.
- Formatting problems. Text justification and zigzag conversion are mostly careful bookkeeping. Write small helper functions (for example, "pad this line to width") and test each one on paper.
- Common prefix across strings. Compare column by column, stopping at the shortest string or the first mismatch; or sort and compare only the first and last strings.
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
- 1. Merge Strings Alternately
- 2. Merge Sorted Array
- 3. Majority Element
- 4. Longest Common Prefix
- 5. Can Place Flowers
- 13. Running Balance Ledger
- 14. Biggest Mirror From Letters
- 18. Count the Strict Peaks
- 19. Runner-Up Value
- 20. Secret Shift Message
- 21. Zeros to the Front
- 22. Sorted Squares From Both Ends
- 23. Diagonal Gap
- 24. Turn Rows Into Columns
- 25. Mirror and Invert a Bitmap
- 26. Row Minimum, Column Maximum
- 27. Email Local-Part Masker
- 28. Longest Letter Streak
- 29. One-Way Trend
- 30. The Missing Ticket
- 31. Doubled and Skipped
- 32. Matching Value Pairs
- 33. How Many Are Smaller
- 34. Is It a Ridge?
- 35. Best View to the Right
- 36. Out of Place in the Lineup
- 37. Flip Only the Letters
- 38. Mirror Each Word
- 39. First Solo Character
- 40. Same Bag of Letters
- 41. Drone Back at Base
- 42. Carousel Match
- 43. Built From One Tile
- 44. Binary String Sum
- 45. Long Decimal Sum
- 46. Odometer Tick
- 47. Sheet Column to Index
- 48. Index to Sheet Column
- 49. Read a Roman Numeral
- 50. Row k of the Number Triangle
- 51. Longest Streak of Ones
- 52. Compact the Sorted List
- 53. Constant Diagonals
- 54. Blur the Picture
- 55. Regrid the Cells
- 56. Restore the Tagged Sentence
- 57. Podium Labels
- 58. Best Product of Three
- 59. Longest Triangle Fence
- 60. Closest Value Pairs
- 61. Parity Matches Index
- 62. Absent From the Roll
- 63. Busiest Census Year
- 64. Squeeze the Repeats
- 65. Angle Between the Hands
- 66. Total Sprinkler Time
- 67. Minimum Safe Start
- 68. Common Items With Repeats
- 69. A Value and Its Double
- 70. Order by Reference
- 71. Licence Code Groups
- 72. Does the Short Form Match?
- 73. Range Summary Lines
- 74. Best Binary Cut
- 75. Distance to the Nearest Marker
- 76. Top Unblocked Word
- 77. One Swap From Twins
- 78. Balanced Bit Blocks
- 79. Fewest Edits to a Mirror
- 80. Shadows of a Block Tower
- 81. Paint for a Block Tower
- 82. Local Maxima Grid
- 83. Rotation Makes Equal
- 84. Slide the Grid
- 85. Is It a Word Square?
- 86. Three Equal Parts by Sum
- 87. Best Single Trade
- 88. Farthest Different Houses
- 89. Where Does the Pattern Start?
- 90. Checkpoints on One Line
- 91. Tic-Tac-Toe Outcome
- 92. Closest Two Names
- 93. Sort by Rarity
- 94. Gather the Tokens
- 95. Even Out the Spaces
- 96. Letters and Digits Alternate
- 97. Words Inside Other Words
- 98. Unsorted Columns
- 99. Fill the Blanks
- 158. Complex Product Text
- 181. Smallest by Same-Parity Swaps
- 183. Reverse Every k-Block
- 266. Rows of Words Within Width
- 268. Double and Sweep
- 271. Lucky Grid Lines
- 272. Nearest Same Value Distance
Medium
- 6. Rotate Array
- 7. Reverse Words in a String
- 8. Increasing Triplet Subsequence
- 9. Zigzag Conversion
- 10. Spiral Matrix
- 15. Quarter Turn In Place
- 16. Wipe Rows and Columns
- 17. Zigzag Diagonal Walk
- 100. Colony Next Generation
- 101. Product of the Others
- 102. Next Arrangement Up
- 103. Seen Exactly Twice
- 104. The Repeated Value
- 105. Three-Colour Sort
- 106. Votes Over a Third
- 107. Researcher Impact Score
- 108. Fuel Stop Loop
- 109. Parse a Whole Number
- 110. Number to Roman Numeral
- 111. Long Multiplication on Strings
- 112. Compare Release Tags
- 113. Tidy a File Path
- 114. Longest Mirror Substring
- 115. Count Mirror Substrings
- 116. Nine-by-Nine Board Check
- 117. Count the Fleets
- 118. Reveal the Field
- 119. Reachable Noughts Board
- 120. Crush the Candy Board
- 121. Sort Each Diagonal
- 122. Neighbourhood Totals
- 123. Count All-Ones Squares
- 124. Longest Ones Line in Any Direction
- 125. Cut Through the Fewest Bricks
- 126. Range Letter Shifts
- 127. Split Into Letter Zones
- 128. Fewest Pieces With Unique Letters
- 129. No Twin Neighbours
- 130. Alphabet by House Rules
- 131. Letters by Popularity
- 132. Dense Rank Labels
- 133. Up-Down Shuffle
- 134. Alternate Gains and Losses
- 135. Spatula Sort
- 136. Make Badge Numbers Unique
- 137. Longest Index Loop
- 138. Fewest Swaps to Sort
- 139. Exactly k Distinct Step Sizes
- 140. Windows With a Peak in Bounds
- 141. Sortable Blocks
- 142. Longest Hill
- 143. Longest Seesaw Run
- 144. Shortest Window to Fix
- 145. Widest Sorted Gap
- 146. Line Up by the Taller Count
- 147. Toppling Tiles
- 148. Codebreaker Feedback
- 149. Replace at Positions
- 150. Stretchy Greetings
- 151. One Edit Apart
- 152. Make a Dice Row Uniform
- 153. One Swap Smaller
- 154. Next Number With the Same Digits
- 155. Best Single Digit Swap
- 156. Latest Clock From Four Digits
- 157. Repeating Decimal Text
- 159. Fraction Chain Sum
- 160. Solve for x
- 161. What Kind of Address?
- 162. Say What You See
- 163. Character in the Expanded Tape
- 164. Bold the Keywords
- 165. Windows With an Odd Total
- 166. All-Zero Stretches
- 167. Meet at the Median
- 168. Raise All but One
- 169. Longest Wobble
- 170. Pair Each With Its Double
- 171. Fewest Edits to Alternate
- 172. Deal Into Straights
- 173. Pattern Repeated k Times
- 174. Split Into Ladders
- 175. Distinct ORs of Subarrays
- 176. Make Letter Tallies Distinct
- 177. Largest Plus in a Field
- 178. Fewest Replacements to an Anagram
- 179. Build the Target With Two Ops
- 180. Off-by-One Substring Pairs
- 182. Split in Three With Equal Ones
- 184. Fewest Flips to Rising Bits
- 185. Prefix-and-Suffix Word Pairs
- 186. Slide L and R
- 187. Shortest Run to Light Every Channel
- 188. Banner Repeats on a Screen
- 189. Richest Window of Distinct Prices
- 190. Undo the Brackets
- 191. Longest Unshared Subsequence
- 192. DNA Complement Mirrors
- 193. How Many Are Hidden Inside?
- 194. Fewest Copies to Spell
- 196. Capital Pattern Queries
- 197. Read Down the Columns
- 198. Files With Twin Contents
- 199. Domain Visit Tally
- 200. Sort the Journal
- 201. Shortest Clock Gap
- 202. Next Time With the Same Digits
- 203. Upside-Down Numbers
- 204. Disjoint Word Product
- 205. Longest Balanced-Case Substring
- 206. Substrings With At Most One Odd Letter
- 207. Peel Matching Ends
- 208. Grandest Merge
- 209. One Step Back Letters
- 210. Smallest Word With a Weight
- 211. Spoil the Mirror
- 212. Rover With Obstacles
- 213. Does the Rover Stay Close?
- 214. Skyline-Safe Raise
- 215. Flip Columns for Uniform Rows
- 216. Best Binary Row Score
- 217. Grid From Its Margins
- 218. Servers That Can Talk
- 219. Rows Equal to Columns
- 220. First Full Line Painted
- 221. Rotate the Grid Rings
- 222. Sorted Grid Lookup
- 223. Level the Grid
- 224. Best Hourglass
- 225. Rectangles With Ones at Corners
- 226. Best Overlay of Two Images
- 227. Tip the Box of Stones
- 228. Heavy-Left Cuts
- 229. Fairest Split Index
- 230. Distance Sums on a Sorted List
- 231. Best Contiguous Total
- 232. Best Total on a Ring
- 233. Best Contiguous Product
- 234. Rotate or Sort the Queue
- 235. Repeat Until It Fits Inside
- 236. Compare by Smallest-Letter Frequency
- 237. Count Triangle Triples
- 238. Equidistant Triples
- 239. Two Plots Coverage
- 240. Four Corners Make a Square?
- 241. Smallest Axis Rectangle From Points
- 242. Points per Circle
- 243. Max Left Under Min Right
- 244. Bracket Balance Swaps
- 245. Split the Nesting Depth
- 246. Total Bit Disagreements
- 247. One-Bit Cycle
- 248. Squads of Three
- 249. Take From Both Ends
- 250. Song Pairs That Fill Hours
- 251. Reverse-Twin Pairs
- 252. Equal Product Quadruples
- 253. Fair Letter Split
- 254. Even-Vowel Stretch
- 255. Most Lamps on One Spot
- 256. No Middle Averages
- 257. Tallest After Trimming
- 258. Mirror From Two-Letter Tiles
- 259. Best Turntable Score
- 260. Two Separate Windows
- 261. Near-Twin Words
- 262. Drop Columns to Order the Rows
- 263. Count Repeated Segments
- 264. Spiral Coordinates From a Start Cell
- 265. Group by Shift Pattern
- 267. Letter Runs on a Wheel
- 269. Strided Sum Queries
- 270. Equal Vowel-Consonant Substrings
- 273. Sum of Distances to Equals
- 274. Cumulative Letter Push
- 275. Pairs With Equal Total Skill
- 276. Find in a Row-Major Grid
- 278. Rubbish Rounds
- 298. k-th Arrangement of 1..n
- 323. Count Anagram Sentences
- 338. Make the Grid Upper-Triangular
- 363. Raise Ranges to the Target
- 365. Window With a Given Hash
Hard
- 11. Text Justification
- 12. First Missing Positive
- 195. Spoken Number Words
- 277. Sum of Floor Ratios
- 279. Smaller to the Right
- 280. Shortest Mirror by Prepending
- 281. Longest Border
- 282. Longest Repeated Substring
- 283. Count Distinct Substrings
- 284. Two Odd Mirrors
- 285. Best Rotation Score
- 286. Into a Checkerboard
- 287. Sortable Blocks With Repeats
- 288. Password Fixer
- 289. True or False Expression
- 290. Molecule Atom Count
- 291. Markup Validator
- 292. Shortest Window Holding a Subsequence
- 293. Total Subsequence Widths
- 294. Unique Letter Score Sum
- 295. Nearest Mirror Number
- 296. Smallest All-Ones Base
- 297. k-th in Dictionary Order
- 299. Fewest Neighbour Swaps to a Mirror
- 300. Swaps to the k-th Bigger Number
- 301. Keep Equal Letters Apart
- 302. Toggle the Grid to Zero
- 303. Stamp the Target
- 304. Partners Side by Side
- 305. First Day With a Gap of k
- 306. Area Under Many Rectangles
- 307. Exact Tiling Check
- 308. Does the Path Cross Itself?
- 309. Reach by Adding
- 310. Cheapest Common Level
- 311. Fewest Edits to a Consecutive Run
- 312. Shortest Window Reaching a Total
- 313. Windows With Fixed Extremes
- 314. Windows With Median k
- 315. Three Disjoint Windows
- 316. Flip k at a Time
- 317. Shortest Unique Abbreviations
- 318. Mirror Chunk Split
- 319. Prefix Match Score Sum
- 320. Most Prefix Deletions
- 321. Smallest Subsequence With a Letter Quota
- 322. Largest Number From Two Rows
- 324. Distinct Good Binary Subsequences
- 325. Five-Digit Mirror Subsequences
- 326. Mini Lisp Evaluator
- 327. Brace Set Expansion
- 328. Is It a Number?
- 329. Longest Balanced Brackets
- 330. Reorder Special Bit Strings
- 331. All Codes Sequence
- 332. Best Window Around an Index
- 333. Fence Around the Trees
- 334. Patch to Cover 1..n
- 335. Same Average Split
- 336. Triplets in Order in Both
- 337. Numbers From a Digit Set
- 339. Count Ones Pyramids
- 340. Lamp Grid Queries
- 341. Puzzle Word Matches
- 342. Cheapest and Dearest Bag Splits
- 343. How Often Does One Repeat Fit Another?
- 344. Most Long Mirrors Without Overlap
- 345. Equal Circular Window Sums
- 346. Total Imbalance of Subarrays
- 347. Gather k Ones Together
- 348. Longest Rearrangeable Mirror Substring
- 349. Shortest Missing Roll Sequence
- 350. Cheapest Fix for Matching Slots
- 351. Longest Strictly Rising Cell Hops
- 352. String From an LCP Table
- 353. Most Beautiful k Distinct Letters
- 354. Split Values to Sort
- 355. Count 1-3-2-4 Patterns
- 356. Echo Substrings
- 357. Greatest Suffix
- 358. Cheapest Removal Keeping a Subsequence
- 359. Longest k-Times Subsequence
- 360. Split a Message With Part Tags
- 361. Fewest Deletions for a Divisor
- 362. Longest Battery Run
- 364. Keep Columns Sorted Across Rows
- 366. Steps to a Sorted String