Created
May 31, 2022 07:36
-
-
Save Shaddyjr/75d4ce209a7164be627da756644742ee 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/absolute-permutation/problem | |
# video: https://youtu.be/Z0bpJiVz0no | |
def absolutePermutation(n, k): | |
if k == 0: # no need to swap anything | |
return list(range(1, n + 1)) | |
cache = set(range(1, n + 1)) # O(n) | |
output = [] | |
for i in range(1, n + 1): # O(n) | |
lower = i - k | |
upper = i + k | |
if lower in cache: | |
cache.remove(lower) | |
output.append(lower) | |
elif upper in cache: | |
cache.remove(upper) | |
output.append(upper) | |
else: | |
return [-1] | |
return output # total time complexity = O(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment