Introduction
Arrays are one of the most commonly used data structures. One must be fluent in array operations to crack coding interviews. Various operations can be performed on an array. In this blog, we will learn how to split the array and add the first part to the end.
Problem Statement
Split the array and add the first part to the end. We split the array into two parts and move the first portion of the array to the end.
Split the array and add the first part to the end
Sample Examples
Example 1
Input:
arr[] = {2, 1, 5, 6, 15, 26}
k = 3
Output:
arr[] = {6, 15, 26, 2, 1, 5}
Explanation:
Split the array and add the first part to the end. In this, we split from index 3 and add the first part {6, 15, 26} to the end.
Example 2
Input:
arr[] = {23, 14, 45}
k = 1
Output:
arr[] = {14, 45, 23}
Explanation:
Split the array and add the first part to the end. In this, we split from index 1 and add the first part {14} to the end.
Also See, Array Implementation of Queue and Rabin Karp Algorithm
Brute Force Approach
To split the array and add the first part to the end, we can rotate the elements of the array one by one.
Pseudocode
Step 1: Initialize the array and the position where we want to split the array.
Step 2: Create a variable to store the element at the 0th position.
Step 3: Replacing each element ‘i’ of the array with the element at the ‘i+1’ position.
Step 4: Replacing the last element of the array with the element stored in the variable created in step 2.
Implementation in C++
#include <iostream>
using namespace std;
// function to split the array and add the first part to the end
void arraySplit(int array[], int j, int k) {
for (int i = 0; i < k; i++) {
// Rotate the array by 1
int x = array[0];
for (int p = 0; p < j - 1; p++)
array[p] = array[p + 1];
array[j - 1] = x;
}
}
// Driver code
int main() {
//initializing the array
int array[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof(array) / sizeof(int);
int pos = 3;
//calling the function
arraySplit(array, n, pos);
// printing the converted array
for (int i = 0; i < n; ++i)
cout << " " << array[i];
return 0;
}
Output:
4 5 6 1 2 3
Complexity Analysis
Time complexity: O(n*k) where n is the size of the array and k is the number of times we have traversed the array. The time complexity is O(nK) as the array is traversed k times.
Space complexity: O(1) as no new memory is created.
Read More - Time Complexity of Sorting Algorithms