Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Created May 31, 2022 07:36
Show Gist options
  • Save Shaddyjr/75d4ce209a7164be627da756644742ee to your computer and use it in GitHub Desktop.
Save Shaddyjr/75d4ce209a7164be627da756644742ee to your computer and use it in GitHub Desktop.
# 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