3. Longest Substring Without Repeating Characters
Asked at 95Bloomberg85Amazon84Microsoft80Google73Meta71Apple69Zoho100Visa96Infosys93Netflix91IBM88Cognizant87Spotify87Yandex86Nvidia85Oracle85persistent systems84Deloitte84Morgan Stanley82Accenture81Tesla74tcs73Agoda69Optum68Goldman Sachs64Media.net57DP world100Freecharge100FreshWorks100Netskope100Splunk100Turing100Walmart Labs100Wissen Technology100Adobe98Yelp94EPAM Systems93ServiceNow92Qualcomm91Rakuten88Sigmoid87TikTok84athenahealth84Docusign82Citigroup81LTI81HashedIn79Accolite79MAQ Software78HCL76Tinkoff75Comcast74Pwc73Zomato73SAP73Wipro73Cisco72Nutanix71Paytm71PayPal71Ozon70Palo Alto Networks70Swiggy69American Express69Coupang68NetApp68Capgemini68Airtel68VK68Dream1168Publicis Sapient68BitGo68Virtusa67Nagarro67Dell66Intel66MakeMyTrip65BNY Mellon65Akamai64Twilio64Zeta64Myntra64eBay64Tekion63Arista Networks60Salesforce57Expedia54DE Shaw47Rippling46Snap45Lyft43Atlassian42Roblox37LinkedIn32Uber22
Problem
Return the length of the longest substring of s that contains no repeated character.
Example: "abcabcbb" → 3 ("abc"); "bbbbb" → 1
Constraints: length ≤ 5·10⁴; letters, digits, symbols and spaces.
Keep the last index of each char. When s[r] was seen inside the window, jump l past that index.
a b c a b c b b
l r 'a' last at 0 -> l = 1 window "bca"
best = 3
Complexity: O(n) time, O(min(n, alphabet)) space.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
last = {}
l = best = 0
for r, ch in enumerate(s):
if last.get(ch, -1) >= l:
l = last[ch] + 1
last[ch] = r
best = max(best, r - l + 1)
return best
assert Solution().lengthOfLongestSubstring("abcabcbb") == 3
assert Solution().lengthOfLongestSubstring("bbbbb") == 1
assert Solution().lengthOfLongestSubstring("pwwkew") == 3
assert Solution().lengthOfLongestSubstring("abba") == 2
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] last = new int[128];
Arrays.fill(last, -1);
int l = 0, best = 0;
for (int r = 0; r < s.length(); r++) {
char c = s.charAt(r);
if (last[c] >= l) l = last[c] + 1;
last[c] = r;
best = Math.max(best, r - l + 1);
}
return best;
}
}
func lengthOfLongestSubstring(s string) int {
last := map[byte]int{} // char -> last index
l, best := 0, 0
for r := 0; r < len(s); r++ {
if i, ok := last[s[r]]; ok && i >= l {
l = i + 1 // jump past the previous copy
}
last[s[r]] = r
best = max(best, r-l+1)
}
return best
}