Problem Description
Given a string. We need to find the sub string of unique characters with longest length.Examples
Given "abcabcbb", the answer is "abc", which the length is 3.Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
Solution 1: Brute Force Solution
An obvious solution would be to consider all the substrings and return the maximum length. The implementation is also obvious. From each position of the string, we compute the substring with unique characters. Finally we return the length of maximum size substring.Complexity
We are computing substring and each of the location. To compute a substring at a location, we might need to traverse the whole string. So the time complexity of this approach will be $O(n^2)$. The space complexity is $O(1)$.Solution 2: Efficient Solution
This problem can be solved efficiently using two pointers.- Set two pointers start = 0 and cursor = 0.
- Keep increasing cursor until we encounter unique characters.
- When a duplicate character is encountered
- Compute length of the substring of unique characters based upon start and cursor value and update max length.
- Move the pointer start towards right until the repeated character is encountered.
- Repeat steps 2 and 3 until the end.
Implementation
No comments:
Post a Comment