Two ends moving inward
One index at the front and one at the back, each step moving at least one of them toward the middle, until they meet.
- Reach for it when
- The problem says reverse or palindrome, or wants a pair from a sorted array, or the widest container.
- The move
leftstarts at the front andrightat the back, and they gowhile left < right. Every step moves at least one of them toward the middle.- Cost
- O(n) time, O(1) extra space.
The idea
I reversed my name in place this morning, and it came back exactly as it was.
Harper isn't a palindrome.
It came back exactly as it was. We'll come back to it. How do you reverse an array without making a new one?
Swap the two ends. The first letter and the last change places. Then the second and the second to last. Then keep going inward.
Two fingers, one at each end?
left at the front and right at the back. Swap what they point at, then each steps one place toward the middle.
When do they stop?
When they meet. while left < right. After the middle there's nothing left to swap, because every letter past it has already been moved.
And if they don't stop at the middle?
Then they cross, and start swapping back the pairs they've already done.
Is this only for reversing?
No. A palindrome check reads from both ends and stops at the first disagreement. A sorted array lets two ends search for a pair that adds up to something. Every time, each step moves at least one finger inward, and the fingers never pass each other.
Why does that make it fast?
Because the two fingers between them only walk the array once. They start a whole array apart and meet in the middle, so there's at most n steps, whatever happens on each one.
So all the cleverness is in which finger moves.
That, and stopping when they meet.
That is the tool. left starts at the front and right at the back, and the loop runs while left < right. Each step looks at the two ends, does something, and moves at least one of them toward the middle. Because the gap between them shrinks every step, the walk takes one pass: O(n) time, with only two indexes of extra memory.
The shape
This is what you know by heart. It is LeetCode 344: reverse an array of characters in place.
/// LeetCode 344. The characters reversed, in place, by swapping the two ends.
func reverseString(_ s: inout [Character]) {
var left = 0 // the front
var right = s.count - 1 // the back
while left < right { // until they meet in the middle
s.swapAt(left, right)
left += 1 // both move one step inward
right -= 1
}
}It has four parts, and each is there for a reason.
- The two ends.
leftis 0 andrightis the last position,s.count - 1. For an empty arrayrightis -1, and the loop never starts. - The condition.
while left < rightstops when the fingers meet or cross. In an array of odd length they meet on the middle letter, which stays where it is. In an array of even length they cross between the two middle letters. - The work.
swapAtexchanges the two letters in place. The array is a parameter markedinout, so the function changes the caller's array, not a copy. - The steps inward. Both fingers move, because both letters have been dealt with.
Watch it run
Here is "harper" being reversed. Each row is one pass, after the swap.
| left | right | the array after the swap |
|---|---|---|
| 0 | 5 | rarpeh |
| 1 | 4 | rerpah |
| 2 | 3 | reprah |
The answer is "reprah". After the third row left is 3 and right is 2. They have crossed, so the loop stops. Six letters took three swaps: half the length, because every swap puts two letters in place.
Step by step
Reverse an array of characters in place by swapping the ends
This step is the shape itself, LeetCode 344, written from an empty function.
What is new: two fingers that start apart and meet. The loop does not visit every position. It visits every pair of positions that mirror each other, and each pair once.
Here is the loop that does not stop at the middle:
func reverseTwice(_ s: inout [Character]) {
var left = 0
var right = s.count - 1
while left < s.count { // on past the middle
s.swapAt(left, right)
left += 1
right -= 1
}
}On "harper" it gives "harper". After the middle, the fingers have crossed, and each swap undoes one already made. Every pair is swapped twice, back to where it started.
Is it a palindrome?
/// Whether `word` reads the same from the back as from the front.
func readsTheSameBothWays(_ word: String) -> Bool {
let chars = Array(word)
var left = 0
var right = chars.count - 1
while left < right {
if chars[left] != chars[right] { // the two ends disagree
return false
}
left += 1
right -= 1
}
return true // they met without disagreeing
}What is new: the walk can end early. The two ends are compared instead of swapped, and the first pair that disagrees answers no. If the fingers meet without a disagreement, every mirrored pair matched, and the answer is yes. "level" is true, and "lever" is false: the first pair, l and r, already disagrees.
The middle letter of an odd word is never compared. It mirrors itself, so it always matches.
Is it a palindrome, looking only at the letters and digits?
This is LeetCode 125. Spaces, commas and question marks are ignored, and a capital matches its small letter.
/// LeetCode 125. Whether `s` reads the same both ways, looking only at its letters and
/// digits, and not minding capitals.
func isPalindrome(_ s: String) -> Bool {
let chars = Array(s)
var left = 0
var right = chars.count - 1
while left < right {
if !(chars[left].isLetter || chars[left].isNumber) {
left += 1 // the front skips what is not looked at
} else if !(chars[right].isLetter || chars[right].isNumber) {
right -= 1 // and so does the back
} else {
if chars[left].lowercased() != chars[right].lowercased() {
return false
}
left += 1
right -= 1
}
}
return true
}What is new: an end that moves on its own. If the front is not a letter or a digit, only the front moves. If the back is not, only the back moves. Only when both ends are on something worth comparing are they compared, and then both move. Each pass still moves at least one finger inward, so the walk still ends.
lowercased() turns a character into its small form, as a String, so "W" and "w" compare equal. "Was it a car, or a cat I saw?" gives true.
isLetter and isNumber come from "Characters as numbers". isNumber is true for more than the ten digits, but this problem's text holds only the plain printable characters, where it means the digits.
In a sorted array, find the pair that adds up to a target
This is LeetCode 167. The array is sorted, smallest first, and exactly one pair of numbers adds up to the target. Hand back their positions, counted from 1.
/// LeetCode 167. In a sorted array, the positions, counted from 1, of the two numbers
/// that add up to `target`. There is exactly one such pair.
func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
var left = 0
var right = numbers.count - 1
while left < right {
let sum = numbers[left] + numbers[right]
if sum == target {
return [left + 1, right + 1]
} else if sum < target {
left += 1 // too small: move the front up
} else {
right -= 1 // too big: move the back down
}
}
return []
}What is new: moving the end that helps. Add the two ends. If the sum is too small, the front is the only finger that can make it bigger: every number after it is at least as big. If the sum is too big, the back is the only one that can make it smaller. So exactly one finger moves, the one that helps.
Why can the finger that moves be dropped for good? Take the case where the sum is too small. The front number, added to the biggest number still in play, is too small. Added to anything smaller, it is smaller still. So the front number is in no pair that works, and it can go.
For 1, 3, 4, 6, 9 and the target 13 the answer is [3, 5], the 4 and the 9. For the target 9 it is [2, 4].
How many such pairs, using each number once?
/// How many pairs in a sorted array add up to `target`, using each number once at most.
func pairsAddingTo(_ numbers: [Int], _ target: Int) -> Int {
var left = 0
var right = numbers.count - 1
var pairs = 0
while left < right {
let sum = numbers[left] + numbers[right]
if sum == target {
pairs += 1
left += 1 // both are used up: both move
right -= 1
} else if sum < target {
left += 1
} else {
right -= 1
}
}
return pairs
}What is new: what to do when the sum is right. The pair is counted, and both numbers are used up, so both fingers move. For 1, 2, 3, 4, 5, 6 and the target 7 there are 3: 1 and 6, 2 and 5, 3 and 4. For four 2s and the target 4 there are 2. Each 2 is used once.
The squares of a sorted array, in order
This is LeetCode 977. The array is sorted, but it may hold numbers below zero, and their squares are big: -4 squared is 16.
/// LeetCode 977. The squares of a sorted array, sorted.
func sortedSquares(_ nums: [Int]) -> [Int] {
var result = Array(repeating: 0, count: nums.count)
var left = 0
var right = nums.count - 1
var place = nums.count - 1 // fill from the back: the biggest first
while left <= right {
let front = nums[left] * nums[left]
let back = nums[right] * nums[right]
if front > back {
result[place] = front
left += 1
} else {
result[place] = back
right -= 1
}
place -= 1
}
return result
}What is new: filling a result from the back. The biggest square is always at one of the two ends, because the numbers furthest from zero are at the ends. So compare the squares of the two ends, put the bigger one in the last free place of the result, and move that finger inward. Then the next biggest goes in the place before, and so on.
The condition is left <= right this time, not left < right. When the two fingers meet, they meet on a number that still has to be squared and placed. For -4, -1, 0, 3, 10 the answer is [0, 1, 9, 16, 100].
The water two walls hold: their distance times the shorter one
Picture a row of walls of different heights, and pour water between two of them. The water rises until it spills over the shorter wall. So the two walls hold a block of water as wide as the distance between them and as tall as the shorter wall.
/// The water two walls hold: how far apart they are, times the shorter one.
func water(_ heights: [Int], _ i: Int, _ j: Int) -> Int {
(j - i) * min(heights[i], heights[j])
}What is new: only the measuring. For the walls 1, 8, 6, 2, 5, the walls at positions 1 and 4 are 3 apart, and the shorter is 5 high, so they hold 15. The walls between do not matter. This is the measure LeetCode 11 is built on.
Reverse Vowels of a String
The vowels of a word swap places from the two ends inward, and every other letter stays where it is. a, e, i, o and u are vowels, small or capital.
First, is this character a vowel?
/// Whether `c` is a vowel, small or capital.
func isVowel(_ c: Character) -> Bool {
let vowels: Set<Character> = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
return vowels.contains(c)
}A Set of ten characters: the five vowels, small and capital. contains is one step, as "A set" showed.
Next, which positions are swapped? Each end moves inward until it sits on a vowel. Then the two are a pair to swap, and both move on. This is step 3's skipping, with "is it a vowel?" as the test.
/// The positions each swap of LeetCode 345 exchanges: the two ends, each moved inward
/// to a vowel.
func vowelPairs(_ s: String) -> [[Int]] {
let chars = Array(s)
var left = 0
var right = chars.count - 1
var pairs: [[Int]] = []
while left < right {
if !isVowel(chars[left]) {
left += 1
} else if !isVowel(chars[right]) {
right -= 1
} else {
pairs.append([left, right])
left += 1
right -= 1
}
}
return pairs
}For "education" the pairs are [[0, 7], [2, 6]]: the e and the o, then the u and the i. The a in the middle mirrors itself, and stays.
Then the problem itself. Swap each pair instead of writing it down:
/// LeetCode 345. `s` with its vowels in the opposite order.
func reverseVowels(_ s: String) -> String {
var chars = Array(s)
var left = 0
var right = chars.count - 1
while left < right {
if !isVowel(chars[left]) {
left += 1
} else if !isVowel(chars[right]) {
right -= 1
} else {
chars.swapAt(left, right)
left += 1
right -= 1
}
}
return String(chars)
}"education" becomes "odicatuen".
Container With Most Water
Given the heights of a row of walls, which two walls hold the most water? Step 7 measures one pair. This problem asks for the best of all of them.
First, the slow way. Try every pair, as in "Loops and indexes", and keep the best.
/// The most water any two walls hold, trying every pair.
func mostWaterSlowly(_ height: [Int]) -> Int {
var best = 0
for i in height.indices {
for j in (i + 1)..<height.count {
best = max(best, (j - i) * min(height[i], height[j]))
}
}
return best
}For the walls [3, 7, 2, 6, 4, 8, 5] the most is 28. Every pair is a loop inside a loop: O(n²). LeetCode's walls number up to 100,000, which is far too many for that.
Next, the walk inward. Start with the two outer walls: the widest pair there is. Measure it. Then move the shorter wall inward, and measure again, until the two meet.
/// The water held by each pair of walls the inward walk looks at, in order.
func areasAlongTheWalk(_ height: [Int]) -> [Int] {
var left = 0
var right = height.count - 1
var areas: [Int] = []
while left < right {
areas.append((right - left) * min(height[left], height[right]))
if height[left] < height[right] {
left += 1 // move the shorter wall
} else {
right -= 1
}
}
return areas
}On the same walls the areas measured are [18, 25, 28, 6, 12, 4], and the best of them is 28, the same as the slow way. Here is the walk, row by row:
| left | right | left wall | right wall | water | best so far | moves |
|---|---|---|---|---|---|---|
| 0 | 6 | 3 | 5 | 18 | 18 | left |
| 1 | 6 | 7 | 5 | 25 | 25 | right |
| 1 | 5 | 7 | 8 | 28 | 28 | left |
| 2 | 5 | 2 | 8 | 6 | 28 | left |
| 3 | 5 | 6 | 8 | 12 | 28 | left |
| 4 | 5 | 4 | 8 | 4 | 28 | left |
Why moving the shorter wall is safe. Look at the first row. The shorter wall is the left one, 3 high. What is the most water it could hold with any wall at all? Every other partner is closer to it, so the water is narrower. And the water can never be taller than 3, because it spills over the shorter wall. So the left wall's best pair is the one just measured, with the far wall, and nothing it does later can beat it. It can be dropped.
Here is that check written out. For each pair the walk measures, it tries the shorter wall with every partner from the other end inward, and keeps the best:
/// For each pair of walls the inward walk looks at, the most water its shorter wall could
/// hold with any wall from the other end inward. The lesson shows it is the pair itself.
func shorterWallBests(_ height: [Int]) -> [Int] {
var left = 0
var right = height.count - 1
var bests: [Int] = []
while left < right {
var best = 0
if height[left] < height[right] {
for k in (left + 1)...right { // the shorter wall, with every partner
best = max(best, (k - left) * min(height[left], height[k]))
}
left += 1
} else {
for k in left..<right {
best = max(best, (right - k) * min(height[k], height[right]))
}
right -= 1
}
bests.append(best)
}
return bests
}On the same walls it gives [18, 25, 28, 6, 12, 4], exactly the areas the walk measured. Each time, the shorter wall's best is the pair the walk had just measured. Moving the taller wall instead loses that guarantee: on the same walls it finds only 18.
Then the problem itself. Keep the best as you walk:
/// LeetCode 11. The most water any two walls hold.
func maxArea(_ height: [Int]) -> Int {
var left = 0
var right = height.count - 1
var best = 0
while left < right {
best = max(best, (right - left) * min(height[left], height[right]))
if height[left] < height[right] {
left += 1 // the shorter wall can do no better
} else {
right -= 1
}
}
return best
}The lesson's code compared it with the slow way on every row of two to seven walls from 0 to 4 high, 97650 rows. They agree on all of them.
What goes wrong
Not stopping at the middle. A loop that runs past the middle swaps every pair back: "harper" stays "harper". The fingers stop when they meet: while left < right.
< where <= was needed, or the other way. Swapping and comparing stop at left < right, because the middle element needs nothing. Filling a result, as in LeetCode 977, needs left <= right, because the middle element still has to be placed.
Moving the wrong end. In a sorted pair search, move the end that helps: the front when the sum is too small, the back when it is too big. In LeetCode 11, move the shorter wall. Moving the other one can skip the answer.
Skipping past the other finger. When an end skips what it does not want, as in LeetCode 125 and 345, it must stop when it reaches the other finger. Testing left < right in the same loop as the skip keeps them from crossing.
Using one end twice. When a pair is used up, as in step 5, both fingers move. Moving only one could pair the same number again.
Say it back
Where do the two fingers start, and when does the loop stop?
Show the answerHide the answer
left at 0 and right at the last position. The loop stops when they meet or cross: while left < right.
Why is the walk O(n), whatever happens on each step?
Show the answerHide the answer
Each step moves at least one finger inward, and the fingers start one array apart. They meet after at most n steps.
In a sorted array, the sum of the two ends is too small. Which finger moves, and why can its number be dropped?
Show the answerHide the answer
The front. Its number, added to the biggest number left, is too small, so it is in no pair that works.
Why does LeetCode 977 fill its result from the back?
Show the answerHide the answer
The biggest square is always at one of the two ends, so the biggest squares are found first. They go in the last places.
In LeetCode 11, why is it safe to drop the shorter wall?
Show the answerHide the answer
Any other partner is closer, and the water can never rise above the shorter wall. Its best pair is the one just measured.
Why did Harper's name come back unchanged when she reversed it?
Show the answerHide the answer
Her loop did not stop at the middle. It kept swapping until left reached the end, so each pair was swapped twice and put back where it started. Stop when the fingers meet.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | Reverse in place | Easy |
| 2 | Back where it started | Easy |
| 3 | The same both ways | Easy |
| 4 | Only the letters and digits | Easy |
| 5 | The pair in a sorted array | Medium |
| 6 | How many pairs? | Easy |
| 7 | Sorted squares | Easy |
| 8 | The water between two walls | Easy |
| 9 | Is it a vowel? | Easy |
| 10 | Which vowels swap? | Easy |
| 11 | Reverse vowels of a string | Easy |
| 12 | The most water, the slow way | Easy |
| 13 | The walk inward | Medium |
| 14 | The shorter wall's best | Easy |
| 15 | Container with most water | Medium |
These problems are done in the Orithms Mac app.
Every piece of code and every number in a lesson comes from a file that was compiled and run.