Skip to content

Instantly share code, notes, and snippets.

@Julisam
Last active May 21, 2021 10:51
Show Gist options
  • Save Julisam/3d1edd6eef678a176efe1fc6568a7950 to your computer and use it in GitHub Desktop.
Save Julisam/3d1edd6eef678a176efe1fc6568a7950 to your computer and use it in GitHub Desktop.
AlgorithmFriday_Week6
def shiftLeft(arr, numm):
for _ in range(numm): # O(k)
temp = arr[0]
for i in range(len(arr)-1): # O(n)
arr[i] = arr[i+1]
arr[-1] = temp
return arr
def shiftRight(arr, numm):
for _ in range(numm): # O(k)
temp = arr[-1]
for i in range(len(arr)-1,0,-1): # O(n)
arr[i] = arr[i-1]
arr[0] = temp
return arr
def shuffleClass(array, num):
try:
# Check if array None or empty
if array == None or len(array)==0:
return []
# Check if num==0 or array contains only one element
elif num ==None or num%len(array)==0 or len(array)<=1:
return array
else:
# Assume we're given an array of 5 elements,
# Shifting right 7 times is the same as shifting right 2 times i.e. 7%5 of which the later is more optimised
# Likewise, shifting right 4 times is the same as shifting left 1 time of which the later is more optimised
if num<0:
# convert to positive if negative
num = len(array)+num
num %= len(array)
else:
num %= len(array)
# Given an array of size n, we'll only shift n/2 times at most
if num <= len(array)//2:
# print(f"I shift Right {num} times")
return shiftRight(array, num)
else:
# print(f"I shift Left {len(array)-num} times")
return shiftLeft(array, len(array)-num)
except:
return []
@meekg33k
Copy link

Hello @Julisam, thank you participating in Week 6 of #AlgorithmFridays.

You came really close to coming up with the most optimal solution for this problem with the optimization you had on line 26 - 41. That was really smart.

However, your solution didn't pass some of the test cases, more specifically the cases where num had a negative value. I think the error is traceable to line 31: num %= len(array). What do you think?

That said, you are still in the running for the $50 award if you're able to correct in on/before 3.00 pm WAT today.

Thanks once again for participating and see you later today for Week 7 of #AlgorithmFridays.

@Julisam
Copy link
Author

Julisam commented May 21, 2021

Thank you @meekg33k.
I have spotted the error and made adjustments.
My mistake was not testing my solution on all test cases when I revised the code, I only assumed its correct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment