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
Do I have a twin with permutated remainders?
How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?
Mage Armor with Defense fighting style (for Adventurers League bladeslinger)
Arthur Somervell: 1000 Exercises - Meaning of this notation
Why are electrically insulating heatsinks so rare? Is it just cost?
TGV timetables / schedules?
Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?
US citizen flying to France today and my passport expires in less than 2 months
In Japanese, what’s the difference between “Tonari ni” (となりに) and “Tsugi” (つぎ)? When would you use one over the other?
Either or Neither in sentence with another negative
Languages that we cannot (dis)prove to be Context-Free
Why doesn't H₄O²⁺ exist?
Does Unearthed Arcana render Favored Souls redundant?
What typically incentivizes a professor to change jobs to a lower ranking university?
Is it tax fraud for an individual to declare non-taxable revenue as taxable income? (US tax laws)
Can I ask the recruiters in my resume to put the reason why I am rejected?
Writing rule stating superpower from different root cause is bad writing
Font hinting is lost in Chrome-like browsers (for some languages )
How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?
Did Shadowfax go to Valinor?
Finding angle with pure Geometry.
Approximately how much travel time was saved by the opening of the Suez Canal in 1869?
Why not use SQL instead of GraphQL?
Why is consensus so controversial in Britain?
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
$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');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
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
$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
$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
$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
New contributor
answered 8 mins ago
R.RR.R
101
101
New contributor
New contributor
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');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
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');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
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');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
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');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
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