Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1928 from saip7795/sp/min-window-subst…
Browse files Browse the repository at this point in the history
…ring

Create: 0076-min-window-substring.rb
  • Loading branch information
tahsintunan authored Jan 9, 2023
2 parents 5378a9e + 3a5138e commit af81849
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions ruby/0076-min-window-substring.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

def min_window(s, t)

return "" if t == ""
count_t = Hash.new(0)
window = Hash.new(0)

t.each_char do |c|
count_t[c] +=1
end

have = 0
need = count_t.length

res = [-1,-1]
result_length = 9999999999
l = 0
(0..s.length-1).each do |r|
c = s[r]
window[c] +=1

have +=1 if ((count_t.keys.include?(c)) && (window[c] == count_t[c]))
while(have == need)
if (r-l+1) < result_length
res = [l,r]
result_length = (r-l+1)

end
window[s[l]] -=1
have -=1 if ((count_t.keys.include?(s[l])) && (window[s[l]] < count_t[s[l]]))
l +=1
end
end
l = res[0]
r = res[1]
if result_length != 9999999999
return s[l..r]
else
return ""
end
end

0 comments on commit af81849

Please sign in to comment.