Created
July 31, 2015 11:22
-
-
Save oskar-j/48c73391f989bea3a3af to your computer and use it in GitHub Desktop.
Tells whether max 1 swap is needed to sort an array in Python
This file contains 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
from itertools import tee, izip | |
from copy import copy | |
def pairwise(seq): | |
a, b = tee(seq) | |
b.next() | |
return izip(a, b) | |
def solution(A): | |
# O(N log(N)) but I think we can do better | |
ordered = True | |
for current_item, next_item in pairwise(A): | |
if current_item > next_item: | |
ordered = False | |
break | |
if ordered: | |
return True | |
unsorted_array = copy(A) | |
A.sort() # timsort takes O(n logn) | |
count = 0 | |
for n, elem in enumerate(A): | |
if unsorted_array[n] != elem: | |
if count < 2: | |
count += 1 | |
else: | |
return False | |
return True | |
print solution([1, 5, 3, 3, 7]) # returns True, swap one (5,3) to get sorted array | |
print solution([1, 3, 3, 3, 7]) # returns True because list is already sorted | |
print solution([1, 3, 5, 3, 4]) # returns False, 2 swaps are needed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment