Reverse Array in Java: 3 Approaches

#Coding3 Q: Reverse an array(Java). Example: int[] arr = {2, 7, 4, 3, 9}; Output → {9, 3, 4, 7, 2} I explored 3 different approaches: ✅ 1. Two Pointer Technique (Optimal – O(n), O(1)) int left = 0; int right = arr.length - 1; while(left < right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } ✅ 2. Using Extra Array (O(n) space) int[] arr = {2, 7, 4, 3, 9}; int[] newArray = new int[arr.length]; int j = 0; for(int i = arr.length - 1; i >= 0; i--) { newArray[j++] = arr[i]; } ✅ 3. Using Streams + Collections List<Integer> newArray = Arrays.stream(arr) .boxed() .collect(Collectors.toList()); Collections.reverse(newArray); Key Learnings: Two-pointer approach is interview preferred (no extra memory) Extra array is simple but uses additional space Streams approach is clean but not optimal Practicing fundamentals consistently to strengthen problem-solving skills #DSA #Java #Arrays #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic #LinkedInDSA

To view or add a comment, sign in

Explore content categories