Optimized Array Rotation in Java with Reversal Algorithm

🚀 Day 1 of My Coding Challenge Today I solved an interesting problem on Array Rotation using Java. 🔹 Problem: Rotate an array to the left by ‘d’ positions efficiently. 🔹 Approach: Instead of shifting elements one by one, I used the Reversal Algorithm: 1️⃣ Reverse first d elements 2️⃣ Reverse remaining elements 3️⃣ Reverse entire array 🔹 Example: Input: [1, 2, 3, 4, 5], d = 2 Output: [3, 4, 5, 1, 2] 🔹 What I learned: ✔ Optimized solution from O(n*d) → O(n) ✔ Importance of breaking problems into smaller steps ✔ In-place array manipulation 💻 Code: ```java import java.util.Arrays; class Solution { public static int[] reverse(int[] arr, int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } return arr; } static int[] rotateArr(int arr[], int d) { int n = arr.length; d = d % n; if (d < 0) { d = d + n; } reverse(arr, 0, d - 1); reverse(arr, d, n - 1); reverse(arr, 0, n - 1); return arr; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int d = 2; int[] res = rotateArr(arr, d); System.out.println(Arrays.toString(res)); } } ``` #Java #DSA #CodingChallenge #50DaysOfCode #LearningJourney #PlacementPreparation

To view or add a comment, sign in

Explore content categories