Advertisement
nirajs

nutanix 1

Feb 5th, 2024
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. '''
  2. Given a string s, find the length of the longest substring without repeating characters.
  3. Input: s = "abcabcbb"
  4. Output: 3
  5.  
  6.  
  7.  
  8. left pointer  0
  9. right pointer 0
  10.  
  11. expand right pointer till we can make substring with non repeating
  12.  
  13. abcabcbb
  14.  
  15. left =  0
  16. right = 0
  17.  
  18. hashmap -> (a 1,b 1,c 1)
  19. abcabcbb
  20. 3
  21.  
  22. a | bc | a
  23.  
  24. bacabc
  25. left = 2
  26. right = 4
  27.  
  28. left
  29. right
  30.  
  31. I try to maximize window  by exapnding right pointers toward right
  32.  
  33. shrink by increamsing left
  34.  
  35.  
  36. '''
  37.  
  38.  
  39. from collections import defaultdict
  40.  
  41. def longestSubstring(s) -> int:
  42.     freqCount = defaultdict(int)
  43.        
  44.     left = 0
  45.     maxSubstring = 0
  46.     for right in range(len(s)):
  47.         c = s[right]
  48.        
  49.         # shrink
  50.         while (freqCount[c] > 0):
  51.             freqCount[s[left]] -=1
  52.             left += 1
  53.            
  54.         freqCount[c] += 1
  55.         maxSubstring = max(maxSubstring, right - left + 1)
  56.        
  57.    
  58.     return maxSubstring
  59.    
  60. s = "aaaaa"
  61. print(longestSubstring(s))
  62.        
  63.        
  64.        
  65.    
  66.    
  67.        
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement