Today we will be going over the "Longest Substring Without Repeating Characters" problem provided by Leetcode.
Longest Substring Without Repeating Characters
In this problem, we need to find the length of the longest substring without repeating characters, given a string.Solution
I first started with a brute force solution. However, I quickly learned how large strings can get and how slowly this solution was.
I then came up with a new solution. In this new solution will utilize two points called "i" and "j". "i" will start at the first index of the string, while "j" starts at the second index of the string. The idea is that "i" marks the beginning of a substring, while "j" will traverse the string until it hits a character it already seen before. When this happens, "i" is set the the index of "j" and "j" is set to be "i + 1". Although this solution is faster than the brute force solution, I wasn't able to past the tests:
The reason I was not able to pass this test, and any other tests past this, was because my second solution was skipping over the substring "vdf" because "i" would be set to an index value of 2 when "j" hits the second "d" in the string.To fix this issue, I made it so that when "j" hits a repeated character, we set "i" to be "i + 1", so then we do not miss substrings like "vdf" in the string "dvdf."
Results
With the last solution I came up with, I was able to have a fast runtime of 68 ms. Although it is fast, looking at the runtime distribution for this problem I was on the slow end of the curve. There was one solution that apparently had a runtime of 0 ms, which is incredible! When it comes to memory, I was on the low end of the curve, so I think that is pretty good.
Conclusion
It has been a long time since I seen this problem, so the details are pretty scarce. I feel pretty good about the runtime achieved by the passing solution, even if I was on the slow end of the runtime distribution. I found that I still was not finished with the "String to Integer (atoi)" problem, so expect a write up about it soon. Thank you for reading and see you next time!
Link to Source Code: https://github.com/EricFlorin/Leetcode-Solutions/blob/master/Longest%20Substring%20Without%20Repeating%20Characters.cpp