Groupon Interview Question
SDE1sTeam: APi Team
Country: India
Interview Type: Phone Interview
So I tried this but the result isn't as expected
func setCards(blackCards:Int, redCards:Int, k:Int) -> [Int] {
var allCardsArray = [Int](count: blackCards + redCards, repeatedValue: 0)
var index = -1
for var i = 0; i < redCards; i++ {
for var j = 0; j < k; {
index++
if index == allCardsArray.count - 1 {
index = 0
}
if allCardsArray[index] != 1 {
j++
}
}
allCardsArray[index] = 1
}
return allCardsArray
}
setCards(5, redCards: 5, k: 2)
Result:
[1, 1, 0, 1, 0, 1, 0, 1, 0, 0]
func setCards(blackCards:Int, redCards:Int, k:Int) -> [Int] {
var allCardsArray = [Int](count: blackCards + redCards, repeatedValue: 0)
var index = -1
for var i = 0; i < redCards; i++ {
for var j = 0; j < k; {
index++
if index == allCardsArray.count - 1 {
index = 0
}
if allCardsArray[index] != 1 {
j++
}
}
allCardsArray[index] = 1
}
return allCardsArray
}
setCards(5, redCards: 5, k: 2)
Result
[1, 1, 0, 1, 0, 1, 0, 1, 0, 0]
Please correct me if I am wrong.
1. Provided you know the length of the string, create a circular linked list and place the R at K distance to allow the Rs will be eliminated before the B.
2. Iterate and delete the node at K interval.
We have to make 2 for loops
1. for placing red cards
2. find position for red card
We are maintaining an array.
I am placing value "1" where we will place red card.
In 2nd inner loop we have to check for 2 conditions:
1. if Index > array bound .. set it as 0.
2. If we get "1" at any location discard it while counting "K"
Here is the code for it.
SetCards(7, 8, 5)
- Mohit March 05, 2014