DRY RUN
s = "loveleetcode"
c = 'e'
Step 1: Find Positions of 'e'
After the first loop, positionsOfC
will contain: [3, 5, 6, 11]
Step 2: Calculate Shortest Distances
Now, let's go through each character and calculate its shortest distance to any 'e':
- 'l' (index 0):
- Distances to 'e': |0-3| = 3, |0-5| = 5, |0-6| = 6, |0-11| = 11
- Shortest = 3
- 'o' (index 1):
- Distances to 'e': |1-3| = 2, |1-5| = 4, |1-6| = 5, |1-11| = 10
- Shortest = 2
- 'v' (index 2):
- Distances to 'e': |2-3| = 1, |2-5| = 3, |2-6| = 4, |2-11| = 9
- Shortest = 1
- 'e' (index 3):
- Distances to 'e': |3-3| = 0, |3-5| = 2, |3-6| = 3, |3-11| = 8
- Shortest = 0
- 'l' (index 4):
- Distances to 'e': |4-3| = 1, |4-5| = 1, |4-6| = 2, |4-11| = 7
- Shortest = 1
- 'e' (index 5):
- Distances to 'e': |5-3| = 2, |5-5| = 0, |5-6| = 1, |5-11| = 6
- Shortest = 0
- 'e' (index 6):
- Distances to 'e': |6-3| = 3, |6-5| = 1, |6-6| = 0, |6-11| = 5
- Shortest = 0
- 't' (index 7):
- Distances to 'e': |7-3| = 4, |7-5| = 2, |7-6| = 1, |7-11| = 4
- Shortest = 1
- 'c' (index 8):
- Distances to 'e': |8-3| = 5, |8-5| = 3, |8-6| = 2, |8-11| = 3
- Shortest = 2
- 'o' (index 9):
- Distances to 'e': |9-3| = 6, |9-5| = 4, |9-6| = 3, |9-11| = 2
- Shortest = 2
- 'd' (index 10):
- Distances to 'e': |10-3| = 7, |10-5| = 5, |10-6| = 4, |10-11| = 1
- Shortest = 1
- 'e' (index 11):
- Distances to 'e': |11-3| = 8, |11-5| = 6, |11-6| = 5, |11-11| = 0
- Shortest = 0
Final Result
The final shortestDistances
vector will be:
[3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Time and Space Complexity
- Time Complexity: O(n * m), where n is the length of the string and m is the number of occurrences of the character 'c'.
- Space Complexity: O(n), where n is the length of the string (for storing the result).
Optimization Potential
This solution works, but it's not the most efficient. We can optimize it to O(n) time complexity by using two passes through the string: one from left to right and another from right to left. This would eliminate the need for the nested loop.