The first line contains an integer, n, denoting the size of the array. The next line contains n space-separated integers denoting the elements of the array.
The output is handled by the code given in the editor, which would print the array. Given array, arr = [16,13,7,2,1,12]. After reversing the array, arr = [12,1,2,7,13,16]
HackerRank,HackerRank C
A functional approach to this task would be making a variable copy of the original array, iterate each operation making sure each one has two elements (indices) and the first index is less than the second one. Then you can just replace the collection subrange with it reversed subsequence: func performOperations(arr: [Int], operations: [[Int]]) -> [Int] { var arr = arr operations.forEach { guard $0.count == 2, $0[0] < $0[1] else { return } arr.replaceSubrange($0[0]...$0[1], with: arr[$0[0]...$0[1]].reversed()) } return arr } let arr = [640, 26, 276, 224, 737, 677, 893, 87, 422, 30] let operations = [[0, 9], [2, 2], [5, 5], [1, 6], [5, 6], [5, 9], [0, 8], [6, 7], [1, 9], [3, 3]] performOperations(arr: arr, operations: operations) // [87, 422, 30, 737, 224, 677, 893, 640, 26, 276]
Given an array, reverse every sub-array formed by consecutive k elements. Examples:
Approach: Consider every sub-array of size k starting from the beginning of the array and reverse it. We need to handle some special cases. If k is not multiple of n where n is the size of the array, for the last group we will have less than k elements left, we need to reverse all remaining elements. If k = 1, the array should remain unchanged. If k >= n, we reverse all elements present in the array. Below image is a dry run of the above approach: Below is the implementation of the above approach:
Output: 3 2 1 6 5 4 8 7Time complexity of above solution is O(n). This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Article Tags : Practice Tags : |