Last active
November 19, 2024 09:29
-
-
Save Shaddyjr/abd6ac1ca85e9d1d0c83b0807a20025e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# source: https://www.hackerrank.com/challenges/kindergarten-adventures | |
# video: https://youtu.be/9vcrruySa9s | |
def sanitize_index(index, n): | |
# index already valid | |
if 0 <= index and index < n: | |
return index | |
# negative index | |
if index < 0: | |
return n + index | |
# index out of range | |
return index % n # CORRECTION. Thanks to Naman Goyal | |
def solve(t): | |
n = len(t) | |
running_sum_builder = [0] * n | |
for i, value in enumerate(t): # O(n) | |
if not value or value == n: # skip 0 and max value (student never finishes) | |
continue | |
index_to_start_counting = sanitize_index(i - value + 1, n) # add 1 for math | |
index_to_stop_counting = sanitize_index(i + 1, n) | |
# if interval contains first index, then we should increment it by 1, since we're | |
# starting there (we don't care about ending at ) | |
if index_to_stop_counting <= index_to_start_counting: | |
running_sum_builder[0] += 1 | |
running_sum_builder[index_to_start_counting] += 1 | |
running_sum_builder[index_to_stop_counting] -= 1 | |
min_counter = float("inf") | |
best_starting_i = None | |
running_sum = 0 | |
for starting_i, val in enumerate(running_sum_builder): # O(n) | |
running_sum += val | |
if running_sum < min_counter: | |
min_counter = running_sum | |
best_starting_i = starting_i | |
return best_starting_i + 1 # not using zero-indexing | |
# Total Time Complexity = O(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, minor error in Line 12-13
Should be