r/csinterviewproblems • u/qibag • Dec 19 '15
Given an array of integers and a partition index, switch the two partitions of the array in O(1) space and O(n) time.
input:
[1,2,3,4,5,6,7], 4output:
[5,6,7,1,2,3,4]input:
[1,2,3,4,5,6,7], 6output:
[7,1,2,3,4,5,6]Source: onsite interview with private B2B company worth a couple hundred million
14
Upvotes
9
u/33a Dec 19 '15
You can do it in 2 passes. Here is an example:
1
u/imaghostspooooky Dec 25 '15 edited Dec 25 '15
Hey op, as someone that hasn't taken algorithms or data structures can I get some feedback. Sorry for the formatting I'm on mobile, but what about something like this:
Would this be acceptable or would the interview end there?
Edit: fixed mistake
4
u/ArkGuardian Dec 19 '15
Can we create a duplicate array (non-destructive)?
2
u/parlezmoose Dec 19 '15
This one stumped me. All glory to /u/33a
1
u/strollertoaster Dec 19 '15
For the test input you gave, is 4 a 1-based (not 0-based) index then? so 0-based the partition index would be 3?
Also, am I misunderstanding, or this a matter of spoiler, if so, here's a simple solution that works for the given test case.
When I first read the question title, I was imagining that the partition index element would remain where it is, and the two partitions would be swapped around it. It doesn't look like that's the case from the test input though.
0
u/vicky002 Dec 19 '15
We do something like, from the given index (here i = 4) to i = length Print element
and then from
0
u/throughactions Dec 19 '15 edited Dec 19 '15
Solution in Ruby.
I believe this is O(n) space and time. I'm putting some thought into how to get space down to O(1), any suggestions would be welcome/appreciated.
Edit: I updated the gist to remove extra memory assignments, I think this is closer to O(1) space. Does that look correct or am I missing something?
0
u/[deleted] Dec 19 '15
[deleted] — view deleted comment
0
u/[deleted] Dec 19 '15
[deleted] — view deleted comment