Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmPython3 Program to Split the array and add the first part to...

Python3 Program to Split the array and add the first part to the end | Set 2

Given an array and split it from a specified position, and move the first part of array add to the end. 
 

Examples: 
 

Input : arr[] = {12, 10, 5, 6, 52, 36}
            k = 2
Output : arr[] = {5, 6, 52, 36, 12, 10}
Explanation : Split from index 2 and first 
part {12, 10} add to the end .

Input : arr[] = {3, 1, 2}
           k = 1
Output : arr[] = {1, 2, 3}
Explanation : Split from index 1 and first
part add to the end.

 

A O(n*k) solution is discussed here
This problem can be solved in O(n) time using the reversal algorithm discussed below, 
1. Reverse array from 0 to n – 1 (where n is size of the array). 
2. Reverse array from 0 to n – k – 1. 
3. Reverse array from n – k to n – 1.
 

Python3




# Python3 program to Split the array
# and add the first part to the end 
  
# Function to reverse arr[] 
# from index start to end*/
def rvereseArray(arr, start, end):
    while start < end :
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] =temp
        start += 1
        end -= 1
  
# Function to print an array 
def printArray(arr, n) :
    for i in range(n):
        print(arr[i], end = " ")
  
  
# Function to left rotate
# arr[] of size n by k */
def splitArr(arr, k, n):
    rvereseArray(arr, 0, n - 1)
    rvereseArray(arr, 0, n - k - 1)
    rvereseArray(arr, n - k, n - 1)
  
# Driver Code
arr = [12, 10, 5, 6, 52, 36]
n = len(arr)
k = 2
splitArr(arr, k, n)
printArray(arr, n)
  
# This code is contributed 
# by Shrikant13


Output: 
 

5 6 52 36 12 10 

 

Please refer complete article on Split the array and add the first part to the end | Set 2 for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Commit to GfG’s Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.

Last Updated :
24 Jan, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

Ted Musemwa
As a software developer I’m interested in the intersection of computational thinking and design thinking when solving human problems. As a professional I am guided by the principles of experiential learning; experience, reflect, conceptualise and experiment.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments