Builds onBig-O and complexity
01The idea
An array stores items side by side in memory. Each item has an index, starting at 0. Reading or writing a[i] takes O(1) time, because the computer can work out where item i sits.
A string is an array of characters. Most array ideas work on strings too.
Three facts shape how you write array code:
- Index access is O(1), so you can reach any position in one step.
- Inserting or deleting in the middle is O(n), because every later item has to shift.
- Strings in Python and Java cannot change.
s + "x"builds a new string and copies every character. Build a result in a list in Python, or aStringBuilderin Java, and turn it into a string once at the end.
Most array solutions walk the array with one or two indices. You need to be sure what each index means at every step. Write it down: "i is the start of the current group", "j is one past the end". Most array bugs come from an index that is off by one.
02How to spot it
Almost every coding problem uses arrays or strings, so the question is how to walk them. Look for these signals:
- The answer depends on groups of equal items next to each other. Walk with a start index and an end index.
- You must compare each item with the one before it. Start the loop at index 1, or handle index 0 on its own.
- The problem says "in place" or "O(1) extra space". You write into the same array with a second index.
- The problem builds a new string piece by piece. Collect the pieces and join them once.
Watch the limits. A string of length 100,000 needs an O(n) or O(n log n) walk. Repeated slicing or += on strings inside a loop can make it O(n²) without you noticing.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue