Shortest Distance to a Character
Hi folks, long time no see! This problem deals with the time-space trade-off, if you're studying for interviews, please keep that in mind :) Usually problems whose solutions are N^2 and whose N is in the 10,000 range are not really tractable so you should be looking for linear or NLogN solutions. To reduce from an N^2 to an N usually you'll be required to use some extra space. If the optimization function is time, it is usually quite OK to utilize some extra memory. So without further a due, here is today's problem:
https://leetcode.com/submissions/detail/154955695/
Given that N is in the order of 10K, we should try to optimize from the get-go. There is an O(N) solution (technically 3N) with an O(N)-space trade-off:
https://leetcode.com/submissions/detail/154955695/
Given a string
S
and a character C
, return an array of integers representing the shortest distance from the character C
in the string.
Example 1:
Input: S = "loveleetcode", C = 'e' Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Given that N is in the order of 10K, we should try to optimize from the get-go. There is an O(N) solution (technically 3N) with an O(N)-space trade-off:
- Find the index of all characters C in the string
- Store that in an array (call it PosC)
- Augment the array with a cell to the left and one to the right in such a way that the first cell is smaller than any other in the (sorted) array and the last is greater than any other in the array
- Have an index pointing to the beginning of PosC. Call it current
- As you traverse the string, check whether the index in the string is larger than PosC[current + 1]
- If it is, increment current
- Now, all you have to do is check the minimum distance between PosC[current] and PosC[current-1], meaning that as you traverse the string you know for sure that the answer for that position will be inevitably between the two current positions in PosC. Hence no need for a nested loop which would put your code in N^2 territory.
And that's it! Happy coding!!! Marcelo
public class Solution
{
public int[] ShortestToChar(string S, char C)
{
LinkedList<int> pos = new LinkedList<int>();
//O(n)
for (int i = 0; i < S.Length; i++)
if (S[i] == C) pos.AddLast(i);
//O(n)
int[] posC = new int[pos.Count + 2];
posC[0] = -12345;
int index = 1;
foreach (int p in pos)
posC[index++] = p;
posC[index] = Int32.MaxValue;
//O(n)
int current = 0;
int[] retVal = new int[S.Length];
for (int i = 0; i < S.Length; i++)
{
if (i > posC[current + 1]) current++;
retVal[i] = Math.Min(Math.Abs(i - posC[current]), Math.Abs(i - posC[current + 1]));
}
return retVal;
}
}
Nice problem and as always neatly explained solution. Thank you.
ReplyDelete