Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Left Rotate Array by K Places - Optimal Algorithm



Problem Statement

Given an array arr of integers and an integer k, your task is to rotate the array to the left by k positions.

In a left rotation, each element of the array is shifted to the left by one index, and the first elements are moved to the end in order.

The goal is to perform this rotation efficiently using an optimal in-place algorithm with O(n) time and O(1) extra space.

Examples

Input ArraykRotated ArrayDescription
[1, 2, 3, 4, 5]2[3, 4, 5, 1, 2]Shift first 2 elements to the end
[10, 20, 30, 40]0[10, 20, 30, 40]No rotation since k = 0
[7, 8, 9]3[7, 8, 9]k equals array length, so array remains unchanged
[4, 5, 6]5[6, 4, 5]k > n, so we use k % n = 2 → rotate by 2 positions
[1]3[1]Single element remains unchanged regardless of k
[]4[]Empty array remains unchanged

Solution

To rotate an array to the left by k places, we want to move the first k elements to the end while keeping the rest in order. A common brute-force method would be to shift elements one-by-one using a temporary array or repeated swaps. However, that is not optimal for performance.

The optimal approach uses the reversal algorithm, which cleverly reverses parts of the array to achieve the same effect in O(n) time with O(1) space:

  • Step 1: Normalize k using k % n. If k is greater than the array size, this avoids unnecessary full rotations.
  • Step 2: Reverse the first k elements. These will eventually go to the end.
  • Step 3: Reverse the remaining n - k elements.
  • Step 4: Reverse the entire array to complete the rotation.

Handling Special Cases

  • k = 0: No rotation is needed. We return the array as-is.
  • k is a multiple of array length: The array remains unchanged after full rotation cycles.
  • k > n: Normalize k using k % n so we rotate only the extra steps.
  • Empty array: There’s nothing to rotate. Return the same empty array.
  • Single-element array: Any number of rotations will not change the array.

This method is efficient and elegant. It works in all scenarios without needing extra memory or multiple passes through the data.

Visualization

Algorithm Steps

  1. Given an array arr of size n and a value k.
  2. Normalize k using k = k % n to handle overflow.
  3. Reverse the first k elements.
  4. Reverse the remaining n - k elements.
  5. Reverse the entire array to get the final rotated form.

Code

Python
JavaScript
Java
C++
C
def reverse(arr, start, end):
    while start < end:
        arr[start], arr[end] = arr[end], arr[start]
        start += 1
        end -= 1

def left_rotate(arr, k):
    n = len(arr)
    k = k % n
    reverse(arr, 0, k - 1)
    reverse(arr, k, n - 1)
    reverse(arr, 0, n - 1)
    return arr

# Sample Input
arr = [1, 2, 3, 4, 5, 6, 7]
k = 2
print("Rotated Array:", left_rotate(arr, k))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)In all cases, the reversal algorithm performs three full reversals of parts of the array, resulting in linear time complexity.
Average CaseO(n)Regardless of the value of k, the algorithm always reverses the same number of elements in total, leading to consistent linear time.
Average CaseO(n)Even in the worst case (e.g., k = n - 1), the three-reversal strategy still results in traversing each element once, so the complexity is linear.

Space Complexity

O(1)

Explanation: The algorithm operates in-place and uses only a constant number of temporary variables to perform reversals. No additional data structures are needed.

Detailed Step by Step Example

We will left rotate the array by 3 places using the reversal algorithm.

{ "array": [10,20,30,40,50,60,70], "showIndices": true }

Step 1: Reverse the first 3 elements.

{ "array": [10,20,30,40,50,60,70], "showIndices": true, "labels": { "0": "start", "2": "end" }, "highlightIndices": [0,1,2] }
{ "array": [30,20,10,40,50,60,70], "showIndices": true, "labels": { "0": "start", "2": "end" } }

Step 2: Reverse the remaining 4 elements.

{ "array": [30,20,10,40,50,60,70], "showIndices": true, "labels": { "3": "start", "6": "end" }, "highlightIndices": [3,4,5,6] }
{ "array": [30,20,10,70,60,50,40], "showIndices": true, "labels": { "3": "start", "6": "end" } }

Step 3: Reverse the entire array.

{ "array": [30,20,10,70,60,50,40], "showIndices": true, "labels": { "0": "start", "6": "end" }, "highlightIndices": [0,1,2,3,4,5,6] }
{ "array": [40,50,60,70,10,20,30], "showIndices": true, "labels": { "0": "start", "6": "end" } }

Final Rotated Array:

{ "array": [40,50,60,70,10,20,30], "showIndices": true, "highlightIndicesGreen": [4,5,6] }


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M