## One-Swappable Array

### July 24, 2015

Today’s exercise helps somebody with their homework:

Given an array of unique integers, determine if it is possible to sort the array by swapping two elements of the array. For instance, the array [1,2,6,4,5,3,7] can be sorted by swapping 3 and 6, but there is no way to sort the array [5,4,3,2,1] by swapping two of its elements. You may use O(

n) time, where the array hasnintegers, and constant additional space.

Your task is to write a program that determines if an array can be sorted with a single swap. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

In Python.

Objection to the modification of the input array. This was supposed to be only a test.

I convinced myself that there have to be one or two pairs of adjacent numbers that are out of order, and those need to be compared to the numbers that are adjacent to them. To manage the complexity, I created a sort of a generator object, and a filter on it, and requested the first, second, and third such quadruple (a quadruple false when not available). Then the test was easy to write. Three linear scans over the input (two of them to find min and max), constant space for state in the generator, and multiple values should be passed without heap allocation in a quality implementation.

Today I’m telling the sourcecode processor that Scheme is “delphi”.

I tested with the following.

I got the following response.

Oops, I noticed that my derangements filter creates a new short-lived procedure for each window. That may or may not violate the constant-space requirement. I prefer to think it doesn’t, as that memory is immediately reclaimable.

Python solution.

Scan the list to find indexes where the items are out of order. If there are only two, check to see if swapping the two items would place the list in order. Special case if one of the items is first or last in the list.

My solution had a bug: two element arrays that are one-swappable are not handled correctly..

Here is a solution with at least one less bug.

Mike, your index takes O(n) space. Consider a reversed range, for example.

Use a generator expression instead of the list comprehension and only request up to one too many index elements. I haven’t exactly tested the following.

Also, there can be only one index element whenever the swapped integers are adjacent in the list.

A shorter version in Python. Basically the same as my first version, but here generators are used are used for looping. For testing I started to use hypothesis, which makes it easy to generate a lot of test cases. I think I like it.

New and improved:

[…] One-swap sorting problem in common lisp. […]