Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasifimtiazohi/4bc97b87aeaf8b74807f034ab054b8cd to your computer and use it in GitHub Desktop.
Save nasifimtiazohi/4bc97b87aeaf8b74807f034ab054b8cd to your computer and use it in GitHub Desktop.
Contiguous Array
def findMaxLength(self, nums: List[int]) -> int:
#visualize nums as a grpah. if found 0 goes up, if 1 goes down
g=0 #initial position in the graph is zero, g points toward position
longest = 0 #keeps track of longest distance between same points in graph
hm={0:-1} #position 0 at graph is first found at index -1/ before start
for i,n in enumerate(nums):
if n==0:
g+=1
else:
g-=1
if g in hm:
longest=max(longest, i - hm[g])
else:
hm[g]=i #g first found at index i
return longest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment