The Wayback Machine - https://web.archive.org/web/20240818163942/https://www.geeksforgeeks.org/print-left-rotation-array/
Open In App

Print left rotation of array in O(n) time and O(1) space

Last Updated : 12 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of size n and multiple values around which we need to left rotate the array. How to quickly print multiple left rotations?

Examples : 

Input : 
arr[] = {1, 3, 5, 7, 9}
k1 = 1
k2 = 3
k3 = 4
k4 = 6
Output :
3 5 7 9 1
7 9 1 3 5
9 1 3 5 7
3 5 7 9 1
Input :
arr[] = {1, 3, 5, 7, 9}
k1 = 14
Output :
9 1 3 5 7

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

We have discussed a solution in the below post. 
Quickly find multiple left rotations of an array | Set 1

Method I: The solution discussed above requires extra space. In this post, an optimized solution is discussed that doesn’t require extra space.

Implementation:

C++
// C++ implementation of left rotation of
// an array K number of times
#include <bits/stdc++.h>
using namespace std;

// Function to leftRotate array multiple times
void leftRotate(int arr[], int n, int k)
{
    /* To get the starting point of rotated array */
    int mod = k % n;

    // Prints the rotated array from start position
    for (int i = 0; i < n; i++)
        cout << (arr[(mod + i) % n]) << " ";

    cout << "\n";
}

// Driver Code
int main()
{
    int arr[] = { 1, 3, 5, 7, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);

    int k = 2;
  
      // Function Call
    leftRotate(arr, n, k);

    k = 3;
  
      // Function Call
    leftRotate(arr, n, k);

    k = 4;
  
      // Function Call
    leftRotate(arr, n, k);

    return 0;
}
C
#include <stdio.h>

// Function to leftRotate array multiple times
void leftRotate(int arr[], int n, int k)
{
    /* To get the starting point of rotated array */
    int mod = k % n;

    // Prints the rotated array from start position
    for (int i = 0; i < n; i++)
        printf("%d ", arr[(mod + i) % n]);

    printf("\n");
}

int main()
{
    int arr[] = { 1, 3, 5, 7, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);

    int k = 2;

    // Function Call
    leftRotate(arr, n, k);

    k = 3;

    // Function Call
    leftRotate(arr, n, k);

    k = 4;

    // Function Call
    leftRotate(arr, n, k);

    return 0;
}
Java
// JAVA implementation of left rotation
// of an array K number of times
import java.util.*;
import java.lang.*;
import java.io.*;

class arr_rot {
    // Function to leftRotate array multiple
    // times
    static void leftRotate(int arr[], int n, int k)
    {
        /* To get the starting point of
        rotated array */
        int mod = k % n;

        // Prints the rotated array from
        // start position
        for (int i = 0; i < n; ++i)
            System.out.print(arr[(i + mod) % n] + " ");

        System.out.println();
    }

    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 3, 5, 7, 9 };
        int n = arr.length;

        int k = 2;
      
          // Function Call
        leftRotate(arr, n, k);

        k = 3;
      
          // Function Call
        leftRotate(arr, n, k);

        k = 4;
      
          // Function Call
        leftRotate(arr, n, k);
    }
}

// This code is contributed by Sanjal
Python
# Python implementation of left rotation of
# an array K number of times

# Function to leftRotate array multiple times


def leftRotate(arr, n, k):

    # To get the starting point of rotated array
    mod = k % n
    s = ""

    # Prints the rotated array from start position
    for i in range(n):
        print str(arr[(mod + i) % n]),
    print
    return


# Driver code
arr = [1, 3, 5, 7, 9]
n = len(arr)
k = 2

# Function Call
leftRotate(arr, n, k)

k = 3

# Function Call
leftRotate(arr, n, k)

k = 4

# Function Call
leftRotate(arr, n, k)

# This code is contributed by Sachin Bisht
C#
// C# implementation of left
// rotation of an array K
// number of times
using System;

class GFG {

    // Function to leftRotate
    // array multiple times
    static void leftRotate(int[] arr, int n, int k)
    {
        // To get the starting
        // point of rotated array
        int mod = k % n;

        // Prints the rotated array
        // from start position
        for (int i = 0; i < n; ++i)
            Console.Write(arr[(i + mod) % n] + " ");

        Console.WriteLine();
    }

    // Driver Code
    static public void Main()
    {
        int[] arr = { 1, 3, 5, 7, 9 };
        int n = arr.Length;

        int k = 2;
      
          // Function Call
        leftRotate(arr, n, k);

        k = 3;
      
          // Function Call
        leftRotate(arr, n, k);

        k = 4;
      
          // Function Call
        leftRotate(arr, n, k);
    }
}

// This code is contributed by m_kit
JavaScript
<script>
// JavaScript implementation of left rotation of
// an array K number of times

// Function to leftRotate array multiple times
function leftRotate(arr, n, k){
    /* To get the starting point of rotated array */
    let mod = k % n;

    // Prints the rotated array from start position
    for (let i = 0; i < n; i++)
        document.write((arr[(mod + i) % n]) + " ");

    document.write("\n");
}

// Driver Code
let arr = [ 1, 3, 5, 7, 9 ];
let n = arr.length;

let k = 2;
// Function Call
leftRotate(arr, n, k);
document.write("<br>");

k = 3;
// Function Call
leftRotate(arr, n, k);
document.write("<br>");

k = 4;
// Function Call
leftRotate(arr, n, k);

</script>
PHP
<?php
// PHP implementation of 
// left rotation of an
// array K number of times

// Function to leftRotate
// array multiple times
function leftRotate($arr, $n, $k)
{
    // To get the starting
    // point of rotated array
    $mod = $k % $n;

    // Prints the rotated array
    // from start position
    for ($i = 0; $i < $n; $i++)
        echo ($arr[($mod + 
                    $i) % $n]) , " ";

    echo "\n";
}

// Driver Code
$arr = array(1, 3, 5, 7, 9);
$n = sizeof($arr);

$k = 2;

// Function Call
leftRotate($arr, $n, $k);

$k = 3;

// Function Call
leftRotate($arr, $n, $k);

$k = 4;

// Function Call
leftRotate($arr, $n, $k);

// This code is contributed by m_kit
?>

Output
5 7 9 1 3 
7 9 1 3 5 
9 1 3 5 7 



Time Complexity: O(N), as we are using a loop to traverse N times.
Auxiliary Space: O(1), as we are not using any extra space.

Method II: In the below implementation we will use Standard Template Library (STL) which will be making the solution more optimize and easy to Implement.

Implementation:

C++
// C++ Implementation For Print Left Rotation Of Any Array K
// Times

#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Function For The k Times Left Rotation
void leftRotate(int arr[], int k, int n)
{

    // Stl function rotates takes three parameters - the
    // beginning,the position by which it should be rotated
    // ,the end address of the array 
      // The below function will be rotating the array left     
    // in linear time (k%arraySize) times
    rotate(arr, arr + (k % n), arr + n);
    
      // Print the rotated array from start position
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << "\n";
}
// Driver program
int main()
{
    int arr[] = { 1, 3, 5, 7, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
  
      // Function Call
    leftRotate(arr, k, n);


    return 0;
}
C
#include <stdio.h>

// Function For k Times Left Rotation
void leftRotate(int arr[], int k, int n)
{
    int i, temp;

    // Perform k left rotations
    for (i = 0; i < k; i++) {
        // Store the first element of the array
        temp = arr[0];

        // Shift all elements one position to the left
        for (int j = 0; j < n - 1; j++) {
            arr[j] = arr[j + 1];
        }

        // Place the first element at the end
        arr[n - 1] = temp;
    }

    // Print the rotated array
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

// Driver program
int main()
{
    int arr[] = { 1, 3, 5, 7, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;

    // Function Call
    leftRotate(arr, k, n);

    return 0;
}
Java
// Java implementation for print left 
// rotation of any array K times
import java.io.*;
import java.util.*;

class GFG{
    
// Function for the k times left rotation
static void leftRotate(Integer arr[], int k,
                                      int n)
{
  
     // In Collection class rotate function 
     // takes two parameters - the name of 
     // array and the position by which it
     // should be rotated
     // The below function will be rotating
     // the array left  in linear time
     
     // Collections.rotate()rotate the
     // array from right hence n-k
    Collections.rotate(Arrays.asList(arr), n - k); 
    
    // Print the rotated array from start position
    for(int i = 0; i < n; i++)
        System.out.print(arr[i] + " ");
}

// Driver code
public static void main(String[] args) 
{
    Integer arr[] = { 1, 3, 5, 7, 9 };
    int n = arr.length;
    int k = 2; 
    
    // Function call
    leftRotate(arr, k, n);
}
}

// This code is contributed by chahattekwani71
Python
# Python3 implementation to print left 
# rotation of any array K times
from collections import deque 

# Function For The k Times Left Rotation
def leftRotate(arr, k, n):
    
    # The collections module has deque class 
    # which provides the rotate(), which is 
    # inbuilt function to allow rotation
    arr = deque(arr) 
    
    # using rotate() to left rotate by k 
    arr.rotate(-k) 
    arr = list(arr) 
    
    # Print the rotated array from
    # start position
    for i in range(n):
        print(arr[i], end = " ")

# Driver Code
if __name__ == '__main__':
      
    arr = [ 1, 3, 5, 7, 9 ]
    n = len(arr)
    k = 2
  
    # Function Call
    leftRotate(arr, k, n)

# This code is contributed by math_lover
C#
// C# program for the above approach
using System;

class GFG
{
    static void leftRotate(int[] arr, int d,
                           int n)
    {
        for (int i = 0; i < d; i++)
            leftRotatebyOne(arr, n);
    }
 
    static void leftRotatebyOne(int[] arr, int n)
    {
        int i, temp = arr[0];
        for (i = 0; i < n - 1; i++)
            arr[i] = arr[i + 1];
 
        arr[n - 1] = temp;
    }
 
    /* utility function to print an array */
    static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
    }

// Driver Code
public static void Main()
{
    int[] arr = { 1, 3, 5, 7, 9 };
    int n = arr.Length;
    int k = 2; 
    
    // Function call
    leftRotate(arr, k, n);
    printArray(arr, n);
}
}

// This code is contributed by avijitmondal1998.
JavaScript
<script>
// Javascript program for the above approach
function leftRotate(arr, d, n)
{
    for (let i = 0; i < d; i++)
        leftRotatebyOne(arr, n);
}
 
function leftRotatebyOne(arr, n)
{
    let i, temp = arr[0];
    for (i = 0; i < n - 1; i++)
        arr[i] = arr[i + 1];
 
    arr[n - 1] = temp;
}
 
/* utility function to print an array */
function printArray(arr, size)
{
    for (let i = 0; i < size; i++)
        document.write(arr[i] + " ");
}

// Driver Code
let arr = [ 1, 3, 5, 7, 9 ];
let n = arr.length;
let k = 2; 
    
// Function call
leftRotate(arr, k, n);
printArray(arr, n);

// This code is contributed by Samim Hossain Mondal.
</script>

Output
5 7 9 1 3 



Note: the array itself gets updated after the rotation.

Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.

Method III(Using Reversal):

To left rotate an array by “k” units we will perform 3 simple reversals-

  • Reverse the first “k” elements
  • Reverse the last “n-k” elements where n is the size of the array
  • Reverse the whole array

Code-

C++
// C++ Implementation For Print Left Rotation Of Any Array K
// Times

#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Function For The k Times Left Rotation
void leftRotate(int arr[], int k, int n)
{
      // if k>n , k%n will bring k back in range
     k = (k%n);

    reverse(arr,arr+k);
    reverse(arr+k,arr+n);
    reverse(arr,arr+n);
    
      // Print the rotated array from start position
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << "\n";
}
// Driver program
int main()
{
    int arr[] = { 1, 3, 5, 7, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
  
      // Function Call
    leftRotate(arr, k, n);


    return 0;
}
C
#include <stdio.h>

// Function For k Times Left Rotation
void leftRotate(int arr[], int k, int n)
{
    // if k > n, k % n will bring k back in range
    k = (k % n);

    // Reverse the first part of the array (0 to k-1)
    for (int i = 0, j = k - 1; i < j; i++, j--) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // Reverse the second part of the array (k to n-1)
    for (int i = k, j = n - 1; i < j; i++, j--) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // Reverse the entire array
    for (int i = 0, j = n - 1; i < j; i++, j--) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // Print the rotated array
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

// Driver program
int main()
{
    int arr[] = { 1, 3, 5, 7, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;

    // Function Call
    leftRotate(arr, k, n);

    return 0;
}
Java
import java.util.*;

public class Main {

    // Function for k times left rotation
    public static void leftRotate(int[] arr, int k) 
    {
      // if k>arr.length,k%arr.length will bring k back to range
       k%=arr.length;
        // Reverse the first k elements
        reverseArray(arr, 0, k - 1);
      
        // Reverse the remaining n-k elements
        reverseArray(arr, k, arr.length - 1);
      
        // Reverse the entire array
        reverseArray(arr, 0, arr.length - 1);

        // Print the rotated array from start position
        String result = Arrays.toString(arr).replaceAll("\\[|\\]|,|\\s", " ");
        System.out.println(result);
    }

    // Helper function to reverse a section of an array from start to end (inclusive)
    public static void reverseArray(int[] arr, int start, int end) {
        while (start < end) {
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    // Driver code
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9};
        int k = 2;

        // Function Call
        leftRotate(arr, k);
    }
}
Python
# Function for k times left rotation
def leftRotate(arr, k):
    # if k>len(arr) , k%=len(arr) bring k back to range 
    k%len(arr)
    # Reverse the first k elements
    arr = reverseArray(arr, 0, k - 1)
    # Reverse the remaining n-k elements
    arr = reverseArray(arr, k, len(arr) - 1)
    # Reverse the entire array
    arr = reverseArray(arr, 0, len(arr) - 1)

    # Print the rotated array from start position
    print(" ".join(map(str,arr)))

# Helper function to reverse a section of an array from start to end (inclusive)
def reverseArray(arr, start, end):
    while start < end:
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
        start += 1
        end -= 1
    return arr

# Driver code
arr = [1, 3, 5, 7, 9]
k = 2
  
# Function Call
leftRotate(arr, k)
C#
// C# Implementation For Print Left Rotation Of Any Array K
// Times
using System;
using System.Collections.Generic;

class Program 
{
  
    // Driver program
    static void Main(string[] args)
    {
        int[] arr = { 1, 3, 5, 7, 9 };
        int n = arr.Length;
        int k = 2;
        leftRotate(arr, k, n);
        Console.ReadKey();
    }

    // Function For The k Times Left Rotation
    static void leftRotate(int[] arr, int k, int n)
    {
        k%=n;
        Array.Reverse(arr, 0, k);
        Array.Reverse(arr, k, n - k);
        Array.Reverse(arr, 0, n);

        // Print the rotated array from start position
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
        Console.WriteLine();
    }
}
// This code is contributed by Tapesh(tapeshdua420)
JavaScript
// Function for k times left rotation
function leftRotate(arr, k) {
    k%=arr.length
    // Reverse the first k elements
    arr = reverseArray(arr, 0, k - 1);
    // Reverse the remaining n-k elements
    arr = reverseArray(arr, k, arr.length - 1);
    // Reverse the entire array
    arr = reverseArray(arr, 0, arr.length - 1);

    // Print the rotated array from start position
    console.log(arr.join(" "));
}

// Helper function to reverse a section of an array from start to end (inclusive)
function reverseArray(arr, start, end) {
    while (start < end) {
        let temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
    return arr;
}

// Driver code
let arr = [1, 3, 5, 7, 9 ];
let n = arr.length;
let k = 2;
  
// Function Call
leftRotate(arr, k, n);
Kotlin
fun leftRotate(arr: IntArray, k: Int, n: Int) {
    // If k > n, k % n will bring k back in range
    val rotation = k % n

    // Reverse the first part of the array (0 to rotation-1)
    for (i in 0 until rotation / 2) {
        val temp = arr[i]
        arr[i] = arr[rotation - i - 1]
        arr[rotation - i - 1] = temp
    }

    // Reverse the second part of the array (rotation to n-1)
    for (i in 0 until (n - rotation) / 2) {
        val temp = arr[rotation + i]
        arr[rotation + i] = arr[n - i - 1]
        arr[n - i - 1] = temp
    }

    // Reverse the entire array
    for (i in 0 until n / 2) {
        val temp = arr[i]
        arr[i] = arr[n - i - 1]
        arr[n - i - 1] = temp
    }

    // Print the rotated array
    for (i in arr) {
        print("$i ")
    }
    println()
}

fun main() {
    val arr = intArrayOf(1, 3, 5, 7, 9)
    val n = arr.size
    val k = 2

    // Function Call
    leftRotate(arr, k, n)
}
fun leftRotate(arr: IntArray, k: Int, n: Int) {
    // If k > n, k % n will bring k back in range
    val rotation = k % n

    // Reverse the first part of the array (0 to rotation-1)
    for (i in 0 until rotation / 2) {
        val temp = arr[i]
        arr[i] = arr[rotation - i - 1]
        arr[rotation - i - 1] = temp
    }

    // Reverse the second part of the array (rotation to n-1)
    for (i in 0 until (n - rotation) / 2) {
        val temp = arr[rotation + i]
        arr[rotation + i] = arr[n - i - 1]
        arr[n - i - 1] = temp
    }

    // Reverse the entire array
    for (i in 0 until n / 2) {
        val temp = arr[i]
        arr[i] = arr[n - i - 1]
        arr[n - i - 1] = temp
    }

    // Print the rotated array
    for (i in arr) {
        print("$i ")
    }
    println()
}

fun main() {
    val arr = intArrayOf(1, 3, 5, 7, 9)
    val n = arr.size
    val k = 2

    // Function Call
    leftRotate(arr, k, n)
}



Output
5 7 9 1 3 



Note: the array itself gets updated after the rotation.

Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.

 



Previous Article
Next Article

Similar Reads

Python3 Program for Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n)Right (Or clockwise) rotate the given string by d elements (where d &lt;= n). Examples: Input : s = "GeeksforGeeks" d = 2 Output : Left Rotation : "eksforGeeksGe" Right Rotation :
3 min read
Javascript Program for Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n)Right (Or clockwise) rotate the given string by d elements (where d &lt;= n). Examples: Input : s = "GeeksforGeeks" d = 2 Output : Left Rotation : "eksforGeeksGe" Right Rotation :
3 min read
Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n) Right (Or clockwise) rotate the given string by d elements (where d &lt;= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "
15+ min read
Count of elements in array A left after performing deletion/rotation operation based on given conditions
Given two binary arrays, A[] and B[] of size N respectively, the task is to find the number of elements in array A[] that will be left after performing the following operation until no elements can be deleted: If the starting elements of array A[] and B[] are equal, then delete both the elements.Otherwise, append the starting character of array A[]
9 min read
Print a matrix in alternate manner (left to right then right to left)
Given a 2D array, the task is to print the 2D in alternate manner (First row from left to right, then from right to left, and so on). Examples: Input : arr[][2] = {{1, 2} {2, 3}}; Output : 1 2 3 2 Input :arr[][3] = { { 7 , 2 , 3 }, { 2 , 3 , 4 }, { 5 , 6 , 1 }}; Output : 7 2 3 4 3 2 5 6 1 The solution of this problem is that run two loops and print
5 min read
Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc”Changing the character at position 3 to 'a' and c
8 min read
Longest subsequence of a number having same left and right rotation
Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101" on left rotation and string "0101" on right rotat
8 min read
Python3 Program to Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc”Changing the character at position 3 to 'a' and c
3 min read
Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc”Changing the character at position 3 to 'a' and c
3 min read
Python3 Program for Longest subsequence of a number having same left and right rotation
Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101" on left rotation and string "0101" on right rotat
4 min read
Javascript Program for Longest subsequence of a number having same left and right rotation
Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101" on left rotation and string "0101" on right rotat
4 min read
Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab" Query 2: 2nd character is d Query 3: str = "ghab
6 min read
Python3 Program for Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab" Query 2: 2nd character is d Query 3: str = "ghab
2 min read
Javascript Program for Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab" Query 2: 2nd character is d Query 3: str = "ghab
2 min read
What is the difference between Auxiliary space and Space Complexity?
Space complexity and Auxiliary space are two of the most often confused and interchangeably used terms when talking about the space complexity of a certain algorithm: Auxiliary Space: The extra space that is taken by an algorithm temporarily to finish its workSpace Complexity: Space complexity is the total space taken by the algorithm with respect
4 min read
Time and Space complexity of 1-D and 2-D Array Operations
The time and space complexity of one-dimensional and two-dimensional array operations can vary depending on the specific operation. Here, we'll discuss common array operations and provide insights into their time and space complexities for one-dimensional and two-dimensional arrays. One-Dimensional Array Operations: Accessing an Element by Index:Ti
3 min read
Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)
Given an unsorted array of distinct numbers, write a function that returns true if array consists of consecutive numbers. Examples : Input : arr[] = {5, 4, 2, 1, 3} Output : Yes Input : arr[] = {2, 1, 0, -3, -1, -2} Output : YesRecommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We have discussed three different app
6 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Duplicates in an array in O(n) time and by using O(1) extra space | Set-3
Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. It is required that the order in which elements repeat should be maintained. If there is no repeating element present then print -1. Examples: Input :
10 min read
Count frequencies of all elements in array in O(1) extra space and O(n) time
Given an unsorted array of n integers that can contain integers from 1 to n. Some elements can be repeated multiple times and some other elements can be absent from the array. Count the frequency of all elements that are present and print the missing elements. Examples: Input: arr[] = {2, 3, 3, 2, 5}Output: Below are frequencies of all elements 1 -
15+ min read
Find the largest multiple of 3 from array of digits | Set 2 (In O(n) time and O(1) space)
Given an array of digits (contain elements from 0 to 9). Find the largest number that can be made from some or all digits of array and is divisible by 3. The same element may appear multiple times in the array, but each element in the array may only be used once. Examples: Input : arr[] = {5, 4, 3, 1, 1} Output : 4311Input : Arr[] = {5, 5, 5, 7} Ou
15+ min read
Python3 Program to Modify given array to a non-decreasing array by rotation
Given an array arr[] of size N (consisting of duplicates), the task is to check if the given array can be converted to a non-decreasing array by rotating it. If it's not possible to do so, then print "No". Otherwise, print "Yes". Examples: Input: arr[] = {3, 4, 5, 1, 2}Output: YesExplanation: After 2 right rotations, the array arr[] modifies to {1,
3 min read
Design a stack to retrieve original elements and return the minimum element in O(1) time and O(1) space
Our task is to design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be performed with time complexity O(1). To implement SpecialStack, you should onl
15+ min read
Javascript Program to Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in t
3 min read
Time and Space Complexity of DFS and BFS Algorithm
The time complexity of both Depth-First Search (DFS) and Breadth-First Search (BFS) algorithms is O(V + E), where V is the number of vertices and E is the number of edges in the graph. The space complexity of DFS is O(V), where V represents the number of vertices in the graph, and for BFS, it is O(V), where V represents the number of vertices in th
2 min read
Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. A number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear at
11 min read
Print greater elements present on the left side of each array element
Given an array arr[] consisting of N distinct integers, the task is to print for each array element, all the greater elements present on its left. Examples: Input: arr[] = {5, 3, 9, 0, 16, 12}Output:5: 3: 59: 0: 9 5 316: 12: 16 Input: arr[] = {1, 2, 0}Output:1: 2: 0: 2 1 Naive Approach: The simplest approach to solve the problem is to traverse the
10 min read
Find maximum in a stack in O(1) time and O(1) extra space
Given a stack of integers. The task is to design a special stack such that the maximum element can be found in O(1) time and O(1) extra space. Examples: Given Stack : 2 5 1 64 --&gt; Maximum So Output must be 64 when getMax() is called. Below are the different functions designed to push and pop elements from the stack. Push(x) : Inserts x at the to
11 min read
Case-specific sorting of Strings in O(n) time and O(1) space
Given a string str consisting of uppercase and lowercase characters. The task is to sort uppercase and lowercase characters separately such that if the ith place in the original string had an uppercase character then it should not have a lowercase character after being sorted and vice versa.Examples: Input: str = "gEeksfOrgEEkS" Output: eEfggkEkrEO
8 min read
Count Possible Decodings of a given Digit Sequence in O(N) time and Constant Auxiliary space
Given a digit sequence S, the task is to find the number of possible decodings of the given digit sequence where 1 represents 'A', 2 represents 'B' ... and so on up to 26, where 26 represents 'Z'. Examples: Input: S = "121" Output: 3 The possible decodings are "ABA", "AU", "LA" Input: S = "1234" Output: 3 The possible decodings are "ABCD", "LCD", "
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg