17.05. Find Longest Subarray
Description
Given an array filled with letters and numbers, find the longest subarray with an equal number of letters and numbers.
Return the subarray. If there are more than one answer, return the one which has the smallest index of its left endpoint. If there is no answer, return an empty arrary.
Example 1:
Input: ["A","1","B","C","D","2","3","4","E","5","F","G","6","7","H","I","J","K","L","M"] Output: ["A","1","B","C","D","2","3","4","E","5","F","G","6","7"]
Example 2:
Input: ["A","A"] Output: []
Note:
array.length <= 100000
Solutions
Solution 1: Prefix Sum + Hash Table
Thinking
The longest subarray with equally many letters and digits. Counting every pair of ends is quadratic.
Letters as \(+1\) and digits as \(-1\) turn the task into the longest zero-sum subarray, i.e. the farthest pair of equal prefix sums.
\(vis\) stores the first index of each prefix, including \(0\mapsto -1\). A repeat of \(s\) yields a zero-sum \((j,i]\); keep the first index so the span is longest.
The problem requires finding the longest subarray with an equal number of characters and digits. We can treat characters as \(1\) and digits as \(-1\), transforming the problem into finding the longest subarray with a sum of \(0\).
We can use the idea of prefix sums and a hash table vis to record the first occurrence of each prefix sum. We use variables mx and k to record the length and the left endpoint of the longest subarray that meets the conditions, respectively.
Next, we iterate through the array, calculating the prefix sum s at the current position i:
- If the prefix sum
sat the current position exists in the hash tablevis, we denote the first occurrence ofsasj, then the sum of the subarray in the interval \([j + 1,..,i]\) is \(0\). If the length of the current subarray is greater than the length of the longest subarray found so far, i.e., \(mx < i - j\), we updatemx = i - jandk = j + 1. - Otherwise, we store the current prefix sum
sas the key and the current positionias the value in the hash tablevis.
After the iteration, we return the subarray with a left endpoint of k and a length of mx.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Where \(n\) is the length of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |