Emma wants to surprise her father with a beautifully arranged bouquet on his birthday. To help her, her mother, Rosy, gives her N flower sticks numbered 1 to N and instructs her to arrange them in a specific order:
This problem is commonly asked in recruitment drives, particularly in coding assessments. Let’s explore how to solve it efficiently!
The function/method receives three inputs:
num (integer): Number of flower sticks (N).random (integer): The count K of flower sticks to be sorted in ascending order.arr (list of integers): A list representing the lengths of flower sticks.Return a list of integers representing the final bouquet arrangement.
random < num0 < num < 10^6num = 7
random = 3
arr = [8, 3, 6, 7, 2, 9, 5]
[8, 3, 6] should be sorted in increasing order → [3, 6, 8][7, 2, 9, 5] should be sorted in decreasing order → [9, 7, 5, 2][3, 6, 8, 9, 7, 5, 2]
K elements and sort them in ascending order.def arrange_flower_sticks(num, random, arr):
first_part = sorted(arr[:random]) # Sort first K elements in ascending order
second_part = sorted(arr[random:], reverse=True) # Sort remaining elements in descending order
return first_part + second_part # Combine both parts
# Example usage
num = 7
random = 3
arr = [8, 3, 6, 7, 2, 9, 5]
print(arrange_flower_sticks(num, random, arr))
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> arrangeFlowerSticks(int num, int random, vector<int>& arr) {
sort(arr.begin(), arr.begin() + random); // Sort first K elements in ascending order
sort(arr.begin() + random, arr.end(), greater<int>()); // Sort remaining in descending order
return arr;
}
int main() {
vector<int> arr = {8, 3, 6, 7, 2, 9, 5};
int num = 7, random = 3;
vector<int> result = arrangeFlowerSticks(num, random, arr);
for (int val : result) cout << val << " ";
return 0;
}
import java.util.*;
public class FlowerBouquet {
public static List<Integer> arrangeFlowerSticks(int num, int random, List<Integer> arr) {
List<Integer> firstPart = arr.subList(0, random);
List<Integer> secondPart = arr.subList(random, num);
Collections.sort(firstPart); // Sort first K elements in ascending order
secondPart.sort(Collections.reverseOrder()); // Sort remaining in descending order
firstPart.addAll(secondPart);
return firstPart;
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(8, 3, 6, 7, 2, 9, 5);
int num = 7, random = 3;
System.out.println(arrangeFlowerSticks(num, random, arr));
}
}
O(K log K + (N-K) log (N-K))O(1) (in-place sorting)This problem is a great example of using sorting techniques efficiently to solve real-world tasks. It frequently appears in coding assessments, so practicing this will improve your problem-solving skills. Try implementing it in different languages and optimizing your solution further!