Minimum swaps algorithm terminated due to timeoutSPOJ GENERAL: sorting by swaps of distance kHackerrank Insertion Sort Algorithm 1 (creating duplicates to show shifting)Terminated due to timeout Mapping phone numbersDetermining the cardinality of sets defined by recursively following indexesSearching the Array Index & Element EqualityK Messed Array sort in JavaClimbing the Leaderboard: HackerranK, Terminated due to timeoutMinimum number of swaps required to sort the array in ascending orderTwo-sum solution in JavaScriptFind array index with element equality in Python
How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?
Smoothness of finite-dimensional functional calculus
How can bays and straits be determined in a procedurally generated map?
Why "Having chlorophyll without photosynthesis is actually very dangerous" and "like living with a bomb"?
What is the word for reserving something for yourself before others do?
Why does Kotter return in Welcome Back Kotter?
How does strength of boric acid solution increase in presence of salicylic acid?
Adding span tags within wp_list_pages list items
Can divisibility rules for digits be generalized to sum of digits
Dragon forelimb placement
Does Unearthed Arcana render Favored Souls redundant?
Can I ask the recruiters in my resume to put the reason why I am rejected?
What do the dots in this tr command do: tr .............A-Z A-ZA-Z <<< "JVPQBOV" (with 13 dots)
Mathematical cryptic clues
Languages that we cannot (dis)prove to be Context-Free
Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)
TGV timetables / schedules?
Show that if two triangles built on parallel lines, with equal bases have the same perimeter only if they are congruent.
What are the differences between the usage of 'it' and 'they'?
Watching something be written to a file live with tail
Why Is Death Allowed In the Matrix?
Can I make popcorn with any corn?
tikz: show 0 at the axis origin
"You are your self first supporter", a more proper way to say it
Minimum swaps algorithm terminated due to timeout
SPOJ GENERAL: sorting by swaps of distance kHackerrank Insertion Sort Algorithm 1 (creating duplicates to show shifting)Terminated due to timeout Mapping phone numbersDetermining the cardinality of sets defined by recursively following indexesSearching the Array Index & Element EqualityK Messed Array sort in JavaClimbing the Leaderboard: HackerranK, Terminated due to timeoutMinimum number of swaps required to sort the array in ascending orderTwo-sum solution in JavaScriptFind array index with element equality in Python
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
I have been trying to solve this question.
Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.
I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.
function findIndice(arr,i)
let iterator=0
while(arr[iterator]!==i+1)
iterator++
return iterator
function swap(arr,x,y)
let temp=arr[x]
arr[x]=arr[y]
arr[y]=temp
function minimumSwaps(arr)
let i=0;
let counter=0;
let size=arr.length;
for(i=0;i<size-1;i++)
if(arr[i]!==i+1)
let index=findIndice(arr,i)
swap(arr,index,i)
counter++
return counter
javascript algorithm sorting time-limit-exceeded interview-questions
$endgroup$
add a comment |
$begingroup$
I have been trying to solve this question.
Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.
I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.
function findIndice(arr,i)
let iterator=0
while(arr[iterator]!==i+1)
iterator++
return iterator
function swap(arr,x,y)
let temp=arr[x]
arr[x]=arr[y]
arr[y]=temp
function minimumSwaps(arr)
let i=0;
let counter=0;
let size=arr.length;
for(i=0;i<size-1;i++)
if(arr[i]!==i+1)
let index=findIndice(arr,i)
swap(arr,index,i)
counter++
return counter
javascript algorithm sorting time-limit-exceeded interview-questions
$endgroup$
$begingroup$
This is a totally different question... @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 2:26
$begingroup$
Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
$endgroup$
– Gerrit0
Aug 12 '18 at 2:48
$begingroup$
That's okay, Thanks for trying to help :) @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 3:50
add a comment |
$begingroup$
I have been trying to solve this question.
Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.
I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.
function findIndice(arr,i)
let iterator=0
while(arr[iterator]!==i+1)
iterator++
return iterator
function swap(arr,x,y)
let temp=arr[x]
arr[x]=arr[y]
arr[y]=temp
function minimumSwaps(arr)
let i=0;
let counter=0;
let size=arr.length;
for(i=0;i<size-1;i++)
if(arr[i]!==i+1)
let index=findIndice(arr,i)
swap(arr,index,i)
counter++
return counter
javascript algorithm sorting time-limit-exceeded interview-questions
$endgroup$
I have been trying to solve this question.
Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.
I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.
function findIndice(arr,i)
let iterator=0
while(arr[iterator]!==i+1)
iterator++
return iterator
function swap(arr,x,y)
let temp=arr[x]
arr[x]=arr[y]
arr[y]=temp
function minimumSwaps(arr)
let i=0;
let counter=0;
let size=arr.length;
for(i=0;i<size-1;i++)
if(arr[i]!==i+1)
let index=findIndice(arr,i)
swap(arr,index,i)
counter++
return counter
javascript algorithm sorting time-limit-exceeded interview-questions
javascript algorithm sorting time-limit-exceeded interview-questions
edited Aug 11 '18 at 22:12
200_success
131k17157422
131k17157422
asked Aug 11 '18 at 17:11
Ugur YilmazUgur Yilmaz
413
413
$begingroup$
This is a totally different question... @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 2:26
$begingroup$
Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
$endgroup$
– Gerrit0
Aug 12 '18 at 2:48
$begingroup$
That's okay, Thanks for trying to help :) @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 3:50
add a comment |
$begingroup$
This is a totally different question... @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 2:26
$begingroup$
Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
$endgroup$
– Gerrit0
Aug 12 '18 at 2:48
$begingroup$
That's okay, Thanks for trying to help :) @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 3:50
$begingroup$
This is a totally different question... @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 2:26
$begingroup$
This is a totally different question... @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 2:26
$begingroup$
Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
$endgroup$
– Gerrit0
Aug 12 '18 at 2:48
$begingroup$
Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
$endgroup$
– Gerrit0
Aug 12 '18 at 2:48
$begingroup$
That's okay, Thanks for trying to help :) @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 3:50
$begingroup$
That's okay, Thanks for trying to help :) @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 3:50
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
Your algorithm can be summarized by the pseudocode:
for each position in the array
if a position is occupied by the wrong number
find the number that fits into the position
perform a swap
A better algorithm would be:
for each position in the array
if a number is in the wrong location
find the position the number should go
perform a swap
This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.
The full program could look like this (in python, as I don't speak js):
def minimumSwaps(arr):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
swaps = 0
for i in range(0, len(arr)):
while arr[i]-1 != i:
swap(i, arr[i]-1)
swaps += 1
return swaps
$endgroup$
$begingroup$
This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 17:25
1
$begingroup$
@UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
$endgroup$
– Rainer P.
Aug 12 '18 at 18:55
$begingroup$
I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 19:50
$begingroup$
There aren't such cases, I tried the solution above and it was accepted.
$endgroup$
– user158037
Oct 12 '18 at 16:07
add a comment |
$begingroup$
The fastest way so far I tried is
- For each iteration of "i"
- Try to find out from the list ( i - 1, arr.length ) if there is an item misplaced
- If there is an misplaced item, swap it
const minimalSwap = (arr) =>
// don't mutate the original array
let list = [...arr]
// length of the list
const listLen = list.length
// state - total swap
let totalSwap = 0
if (listLen <= 1)
return totalSwap
function swap(items, idxOne, idxTwo)
let tempNode = items[idxOne]
items[idxOne] = items[idxTwo]
items[idxTwo] = tempNode
totalSwap += 1
return items
for (let i = 0; i < listLen; i++)
// for each iteration, we find the
// number that should go to the correct position
let idToSwap = false
const correctNumber = i + 1
// iterate through starting next item
// and find if the correct number is misplaced
for (let j = i + 1; j < listLen; j++)
// if it is misplaced, swap it
if (correctNumber === list[j])
idToSwap = j
break;
if (idToSwap)
list = swap(list, i, idToSwap)
return totalSwap
// test case
minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])New contributor
R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f201470%2fminimum-swaps-algorithm-terminated-due-to-timeout%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Your algorithm can be summarized by the pseudocode:
for each position in the array
if a position is occupied by the wrong number
find the number that fits into the position
perform a swap
A better algorithm would be:
for each position in the array
if a number is in the wrong location
find the position the number should go
perform a swap
This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.
The full program could look like this (in python, as I don't speak js):
def minimumSwaps(arr):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
swaps = 0
for i in range(0, len(arr)):
while arr[i]-1 != i:
swap(i, arr[i]-1)
swaps += 1
return swaps
$endgroup$
$begingroup$
This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 17:25
1
$begingroup$
@UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
$endgroup$
– Rainer P.
Aug 12 '18 at 18:55
$begingroup$
I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 19:50
$begingroup$
There aren't such cases, I tried the solution above and it was accepted.
$endgroup$
– user158037
Oct 12 '18 at 16:07
add a comment |
$begingroup$
Your algorithm can be summarized by the pseudocode:
for each position in the array
if a position is occupied by the wrong number
find the number that fits into the position
perform a swap
A better algorithm would be:
for each position in the array
if a number is in the wrong location
find the position the number should go
perform a swap
This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.
The full program could look like this (in python, as I don't speak js):
def minimumSwaps(arr):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
swaps = 0
for i in range(0, len(arr)):
while arr[i]-1 != i:
swap(i, arr[i]-1)
swaps += 1
return swaps
$endgroup$
$begingroup$
This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 17:25
1
$begingroup$
@UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
$endgroup$
– Rainer P.
Aug 12 '18 at 18:55
$begingroup$
I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 19:50
$begingroup$
There aren't such cases, I tried the solution above and it was accepted.
$endgroup$
– user158037
Oct 12 '18 at 16:07
add a comment |
$begingroup$
Your algorithm can be summarized by the pseudocode:
for each position in the array
if a position is occupied by the wrong number
find the number that fits into the position
perform a swap
A better algorithm would be:
for each position in the array
if a number is in the wrong location
find the position the number should go
perform a swap
This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.
The full program could look like this (in python, as I don't speak js):
def minimumSwaps(arr):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
swaps = 0
for i in range(0, len(arr)):
while arr[i]-1 != i:
swap(i, arr[i]-1)
swaps += 1
return swaps
$endgroup$
Your algorithm can be summarized by the pseudocode:
for each position in the array
if a position is occupied by the wrong number
find the number that fits into the position
perform a swap
A better algorithm would be:
for each position in the array
if a number is in the wrong location
find the position the number should go
perform a swap
This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.
The full program could look like this (in python, as I don't speak js):
def minimumSwaps(arr):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
swaps = 0
for i in range(0, len(arr)):
while arr[i]-1 != i:
swap(i, arr[i]-1)
swaps += 1
return swaps
answered Aug 12 '18 at 10:25
Rainer P.Rainer P.
1,261414
1,261414
$begingroup$
This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 17:25
1
$begingroup$
@UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
$endgroup$
– Rainer P.
Aug 12 '18 at 18:55
$begingroup$
I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 19:50
$begingroup$
There aren't such cases, I tried the solution above and it was accepted.
$endgroup$
– user158037
Oct 12 '18 at 16:07
add a comment |
$begingroup$
This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 17:25
1
$begingroup$
@UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
$endgroup$
– Rainer P.
Aug 12 '18 at 18:55
$begingroup$
I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 19:50
$begingroup$
There aren't such cases, I tried the solution above and it was accepted.
$endgroup$
– user158037
Oct 12 '18 at 16:07
$begingroup$
This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 17:25
$begingroup$
This is a great solution but it fails if the numbers are not consecutive. To illustrate; 1 3 5 2 4 6 8 does not pass this test case @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 17:25
1
1
$begingroup$
@UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
$endgroup$
– Rainer P.
Aug 12 '18 at 18:55
$begingroup$
@UgurYilmaz - Your question literaly says [...] consisting of consecutive integers [...].
$endgroup$
– Rainer P.
Aug 12 '18 at 18:55
$begingroup$
I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 19:50
$begingroup$
I know but there should be an error in hackerRank, then. Because there is a test case with that input and it seems to fail. Do you have any idea how to implement a solution efficiently if it is not a consecutive array integers @Rainer P.
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 19:50
$begingroup$
There aren't such cases, I tried the solution above and it was accepted.
$endgroup$
– user158037
Oct 12 '18 at 16:07
$begingroup$
There aren't such cases, I tried the solution above and it was accepted.
$endgroup$
– user158037
Oct 12 '18 at 16:07
add a comment |
$begingroup$
The fastest way so far I tried is
- For each iteration of "i"
- Try to find out from the list ( i - 1, arr.length ) if there is an item misplaced
- If there is an misplaced item, swap it
const minimalSwap = (arr) =>
// don't mutate the original array
let list = [...arr]
// length of the list
const listLen = list.length
// state - total swap
let totalSwap = 0
if (listLen <= 1)
return totalSwap
function swap(items, idxOne, idxTwo)
let tempNode = items[idxOne]
items[idxOne] = items[idxTwo]
items[idxTwo] = tempNode
totalSwap += 1
return items
for (let i = 0; i < listLen; i++)
// for each iteration, we find the
// number that should go to the correct position
let idToSwap = false
const correctNumber = i + 1
// iterate through starting next item
// and find if the correct number is misplaced
for (let j = i + 1; j < listLen; j++)
// if it is misplaced, swap it
if (correctNumber === list[j])
idToSwap = j
break;
if (idToSwap)
list = swap(list, i, idToSwap)
return totalSwap
// test case
minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])New contributor
R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
The fastest way so far I tried is
- For each iteration of "i"
- Try to find out from the list ( i - 1, arr.length ) if there is an item misplaced
- If there is an misplaced item, swap it
const minimalSwap = (arr) =>
// don't mutate the original array
let list = [...arr]
// length of the list
const listLen = list.length
// state - total swap
let totalSwap = 0
if (listLen <= 1)
return totalSwap
function swap(items, idxOne, idxTwo)
let tempNode = items[idxOne]
items[idxOne] = items[idxTwo]
items[idxTwo] = tempNode
totalSwap += 1
return items
for (let i = 0; i < listLen; i++)
// for each iteration, we find the
// number that should go to the correct position
let idToSwap = false
const correctNumber = i + 1
// iterate through starting next item
// and find if the correct number is misplaced
for (let j = i + 1; j < listLen; j++)
// if it is misplaced, swap it
if (correctNumber === list[j])
idToSwap = j
break;
if (idToSwap)
list = swap(list, i, idToSwap)
return totalSwap
// test case
minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])New contributor
R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
The fastest way so far I tried is
- For each iteration of "i"
- Try to find out from the list ( i - 1, arr.length ) if there is an item misplaced
- If there is an misplaced item, swap it
const minimalSwap = (arr) =>
// don't mutate the original array
let list = [...arr]
// length of the list
const listLen = list.length
// state - total swap
let totalSwap = 0
if (listLen <= 1)
return totalSwap
function swap(items, idxOne, idxTwo)
let tempNode = items[idxOne]
items[idxOne] = items[idxTwo]
items[idxTwo] = tempNode
totalSwap += 1
return items
for (let i = 0; i < listLen; i++)
// for each iteration, we find the
// number that should go to the correct position
let idToSwap = false
const correctNumber = i + 1
// iterate through starting next item
// and find if the correct number is misplaced
for (let j = i + 1; j < listLen; j++)
// if it is misplaced, swap it
if (correctNumber === list[j])
idToSwap = j
break;
if (idToSwap)
list = swap(list, i, idToSwap)
return totalSwap
// test case
minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])New contributor
R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
The fastest way so far I tried is
- For each iteration of "i"
- Try to find out from the list ( i - 1, arr.length ) if there is an item misplaced
- If there is an misplaced item, swap it
const minimalSwap = (arr) =>
// don't mutate the original array
let list = [...arr]
// length of the list
const listLen = list.length
// state - total swap
let totalSwap = 0
if (listLen <= 1)
return totalSwap
function swap(items, idxOne, idxTwo)
let tempNode = items[idxOne]
items[idxOne] = items[idxTwo]
items[idxTwo] = tempNode
totalSwap += 1
return items
for (let i = 0; i < listLen; i++)
// for each iteration, we find the
// number that should go to the correct position
let idToSwap = false
const correctNumber = i + 1
// iterate through starting next item
// and find if the correct number is misplaced
for (let j = i + 1; j < listLen; j++)
// if it is misplaced, swap it
if (correctNumber === list[j])
idToSwap = j
break;
if (idToSwap)
list = swap(list, i, idToSwap)
return totalSwap
// test case
minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])const minimalSwap = (arr) =>
// don't mutate the original array
let list = [...arr]
// length of the list
const listLen = list.length
// state - total swap
let totalSwap = 0
if (listLen <= 1)
return totalSwap
function swap(items, idxOne, idxTwo)
let tempNode = items[idxOne]
items[idxOne] = items[idxTwo]
items[idxTwo] = tempNode
totalSwap += 1
return items
for (let i = 0; i < listLen; i++)
// for each iteration, we find the
// number that should go to the correct position
let idToSwap = false
const correctNumber = i + 1
// iterate through starting next item
// and find if the correct number is misplaced
for (let j = i + 1; j < listLen; j++)
// if it is misplaced, swap it
if (correctNumber === list[j])
idToSwap = j
break;
if (idToSwap)
list = swap(list, i, idToSwap)
return totalSwap
// test case
minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])const minimalSwap = (arr) =>
// don't mutate the original array
let list = [...arr]
// length of the list
const listLen = list.length
// state - total swap
let totalSwap = 0
if (listLen <= 1)
return totalSwap
function swap(items, idxOne, idxTwo)
let tempNode = items[idxOne]
items[idxOne] = items[idxTwo]
items[idxTwo] = tempNode
totalSwap += 1
return items
for (let i = 0; i < listLen; i++)
// for each iteration, we find the
// number that should go to the correct position
let idToSwap = false
const correctNumber = i + 1
// iterate through starting next item
// and find if the correct number is misplaced
for (let j = i + 1; j < listLen; j++)
// if it is misplaced, swap it
if (correctNumber === list[j])
idToSwap = j
break;
if (idToSwap)
list = swap(list, i, idToSwap)
return totalSwap
// test case
minimalSwap([14, 15, 16, 4, 8, 3, 1, 2, 5, 7, 9, 10, 11, 12, 13, 6])New contributor
R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered 20 secs ago
R.RR.R
101
101
New contributor
R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
R.R is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f201470%2fminimum-swaps-algorithm-terminated-due-to-timeout%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
This is a totally different question... @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 2:26
$begingroup$
Oh shoot, you are totally right. I must have sent the wrong link as I looked at several... sorry about that!
$endgroup$
– Gerrit0
Aug 12 '18 at 2:48
$begingroup$
That's okay, Thanks for trying to help :) @Gerrit0
$endgroup$
– Ugur Yilmaz
Aug 12 '18 at 3:50