Part 17 / Topic 2 of 20
Arrays and strings
Python's list is a dynamic array: one contiguous block of memory that grows as needed. That layout is why nums[i] and append are O(1), and why anything that touches the front ā insert(0, x), pop(0) ā is O(n): every other item has to shift one slot. Strings are immutable arrays of characters: every "change" quietly builds a new string.
Think of a row of numbered lockers: jumping straight to locker 7 is instant, but squeezing a new locker in at the front means re-labelling every locker after it.
| Operation | Cost | Why |
|---|---|---|
nums[i], nums.append(x) |
O(1) | direct slot access; append fills pre-grown space |
nums.insert(0, x), nums.pop(0) |
O(n) | everything after the slot shifts |
nums[1:] (any slice) |
O(n) | slicing copies ā it is a new list, not a view |
text += piece in a loop |
O(n²) overall | each += builds a whole new string |
Measured (200,000 appends at the end vs a tenth as many inserts at the front):
200,000 appends at the end: 2.5 ms
20,000 inserts at the front: 53.0 ms (varies by machine)
Ten times fewer operations, yet twenty times slower ā front inserts shift everything. Build strings with join, not +=:
names = ["Ravi", "Asha", "Imran", "Kavya"]
line = ", ".join(names) # one O(n) build
print(line) # Ravi, Asha, Imran, Kavya
A matrix (2D grid) is just a list of rows, and zip(*matrix) regroups it column by column:
sales = [
[12, 15, 9], # Kothrud
[7, 11, 14], # Baner
[10, 8, 13], # Camp
]
print([sum(row) for row in sales]) # [36, 32, 31] per-shop totals
print([sum(col) for col in zip(*sales)]) # [29, 34, 36] per-month totals
Real-world example: a sales dashboard holding "three shops Ć three months" as a grid answers both "how did Baner do this quarter?" (a row) and "how did March go across shops?" (a column) with the two lines above.
ā ļø A slice is a copy:
rest = orders[1:]costs O(n) time and memory, and changingrestnever touchesorders. That protects you from surprises but silently doubles memory if you slice big lists in a loop.
Practice: row/column totals and transposes on small grids; in-place array edits (remove a value, de-duplicate a sorted list); string building and splitting (join, split, reversing words).
Practice on LeetCode - start here: Remove Duplicates from Sorted Array Ā· Plus One Ā· Length of Last Word Ā· Pascal's Triangle Ā· Rotate Array
Show the full practice list (14 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Remove Element | Easy |
| Monotonic Array | Easy |
| Longest Common Prefix | Easy |
| Find the Index of the First Occurrence in a String | Easy |
| Transpose Matrix | Easy |
| Reverse Words in a String | Medium |
| String Compression | Medium |
| Rotate Image | Medium |
| Spiral Matrix | Medium |
| Set Matrix Zeroes | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Game of Life | Medium |
| Spiral Matrix II | Medium |
| Zigzag Conversion | Medium |
| Text Justification | Hard |
Full program: examples/02_arrays_strings.py.
Exercise 2: Arrays and strings ā sales grid report
Scenario: A three-shop chain tracks three months of sales in a grid (rows = shops, columns = months) and wants shop totals, month totals, and a one-line report.
What to do: Write shop_totals(sales) (sum of each row), month_totals(sales) (sum of each column ā zip(*sales) regroups the grid column by column), and report_line(shops, totals) that builds "Kothrud=36, Baner=32, Camp=31" with one ", ".join(...) ā no += string building in a loop. Print all three.
Starting data:
SALES = [
[12, 15, 9], # Kothrud
[7, 11, 14], # Baner
[10, 8, 13], # Camp
]
SHOPS = ["Kothrud", "Baner", "Camp"]
Sample output:
Shop totals: [36, 32, 31]
Month totals: [29, 34, 36]
Report: Kothrud=36, Baner=32, Camp=31
Show the solution to Exercise 2
"""Exercise 2: Arrays and strings - sales grid report.
Row totals come from summing each row; month totals come from
zip(*grid), which regroups the grid column by column. The report line
is built once with join - no += string building in a loop.
Run: python ex02.py (macOS/Linux: python3 ex02.py)
"""
SALES = [
[12, 15, 9], # Kothrud
[7, 11, 14], # Baner
[10, 8, 13], # Camp
]
SHOPS = ["Kothrud", "Baner", "Camp"]
def shop_totals(sales: list[list[int]]) -> list[int]:
return [sum(row) for row in sales]
def month_totals(sales: list[list[int]]) -> list[int]:
return [sum(column) for column in zip(*sales)]
def report_line(shops: list[str], totals: list[int]) -> str:
return ", ".join(f"{shop}={total}" for shop, total in zip(shops, totals))
def main() -> None:
totals = shop_totals(SALES)
print(f"Shop totals: {totals}")
print(f"Month totals: {month_totals(SALES)}")
print(f"Report: {report_line(SHOPS, totals)}")
if __name__ == "__main__":
main()