#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
Reverse Array in Java: 3 Approaches
More Relevant Posts
-
#Coding6 Q: Remove Duplicates from Sorted Array (Java) Example: int[] arr = {1, 1, 2, 2, 3, 4, 4}; Output → {1, 2, 3, 4} Count → 4 I explored 2 different approaches: ✅ 1. Two Pointer Technique (Optimal – O(n), O(1)) static int removeDuplicates(int[] arr) { if(arr.length == 0) return 0; int j = 1; for(int i = 1; i < arr.length; i++) { if(arr[i] != arr[i - 1]) { arr[j++] = arr[i]; } } return j; // number of unique elements } ✅ 2. Using HashSet (Extra Space) Set<Integer> set = new LinkedHashSet<>(); for(int num : arr) set.add(num); int k = 0; for(int num : set) { arr[k++] = num; } Key Learnings: Two-pointer approach is interview preferred (in-place, no extra memory) HashSet approach is simpler but uses extra space Sorted property makes duplicate removal efficient Practicing DSA daily to strengthen problem-solving skills #DSA #Java #Arrays #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
#Coding7 Q: Rotate an Array (Java) Example: int[] arr = {1, 2, 3, 4, 5, 6, 7} k = 3 Output → {5, 6, 7, 1, 2, 3, 4} I explored 3 different approaches: ✅ 1. Reverse Method (Optimal – O(n), O(1)) static void rotate(int[] arr, int k) { k = k % arr.length; reverse(arr, 0, arr.length - 1); reverse(arr, 0, k - 1); reverse(arr, k, arr.length - 1); } static void reverse(int[] arr, int l, int r) { while(l < r) { int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; l++; r--; } } ✅ 2. Using Extra Array (O(n) space) int n = arr.length; int[] temp = new int[n]; for(int i = 0; i < n; i++) { temp[(i + k) % n] = arr[i]; } arr = temp; ✅ 3. Brute Force Approach (O(n × k)) for(int i = 0; i < k; i++) { int last = arr[arr.length - 1]; for(int j = arr.length - 1; j > 0; j--) { arr[j] = arr[j - 1]; } arr[0] = last; } Key Learnings: Reverse method is interview preferred (in-place, no extra memory) Extra array approach is easier but uses additional space Brute force works but is inefficient for large k #DSA #Java #Arrays #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
#Coding4 Q: Check whether a given array is sorted in ascending order. Example: {1, 3, 5, 7, 9} → ✅ Sorted {1, 5, 3, 7} → ❌ Not Sorted I explored 3 different approaches: ✅ 1. Single Pass (Optimal – O(n)) static boolean isSorted(int[] arr) { for(int i = 0; i < arr.length - 1; i++) { if(arr[i] > arr[i + 1]) return false; } return true; } ✅ 2. Using Streams boolean sorted = IntStream.range(0, arr.length - 1).allMatch(i -> arr[i] <= arr[i + 1]); ✅ 3. Compare with Sorted Copy int[] copy = arr.clone(); Arrays.sort(copy); boolean isSorted = Arrays.equals(copy, arr); Key Learnings: Single-pass solution is interview preferred (O(n), O(1)) Streams provide a functional style Sorting approach is simpler but less optimal Practicing fundamentals daily to strengthen problem-solving skills #DSA #Java #Arrays #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
Day 20 of DSA Consistency – LeetCode 15 (3Sum) Today I solved the classic 3Sum problem. Problem: Find all unique triplets in an array such that a + b + c = 0. At first glance, brute force looks easy (O(n³)), but that’s useless for interviews. It will timeout. The correct approach is: • Sort the array • Fix one number • Use Two Pointers (2Sum technique) • Skip duplicates carefully This reduces the complexity to O(n²). Key learning: Most “hard” problems are just combinations of simpler patterns. 3Sum = Sorting + Two Pointers + Duplicate handling. Patterns > memorizing solutions. Code (Java): class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<>(); Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue; int left = i + 1, right = nums.length - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum == 0) { res.add(Arrays.asList(nums[i], nums[left], nums[right])); while (left < right && nums[left] == nums[left + 1]) left++; while (left < right && nums[right] == nums[right - 1]) right--; left++; right--; } else if (sum < 0) left++; else right--; } } return res; } } Time Complexity: O(n²) Space Complexity: O(1) Consistency matters more than speed. 20 days done. No breaks. #DSA #LeetCode #Java #ProblemSolving #CodingInterview #SoftwareEngineering #100DaysOfCode
To view or add a comment, sign in
-
🚀 DSA Tip: Two Pointer Approach for Target Sum If your array is sorted, you don’t need nested loops to find a pair with a given target sum. 👉 Use the Two Pointer Technique — simple and O(n)! 💡 How it works: • Place one pointer at the start (left) • Place another at the end (right) • Compare their sum with the target ✅ If sum is small → move left++ ✅ If sum is large → move right-- ✅ If equal → 🎯 pair found ⏱️ Complexity: Time → O(n) Space → O(1) 🔥 When to use: ✔️ Target sum in sorted array ✔️ Pair problems ✔️ Remove duplicates ✔️ Reverse problems Mastering two pointers can save you from unnecessary O(n²) solutions! #DSA #CodingInterview #Java #TwoPointers #ProblemSolving #TechLearning
To view or add a comment, sign in
-
-
Merge Sort in Java may look complex, but most mistakes happen because: • we don’t clearly understand how the array is divided • we mix up the merge logic • we forget that sorting actually happens during the merge step The core idea is straightforward: divide the array into smaller parts, sort them recursively, and then merge them back in sorted order. What really happens: – The array is repeatedly divided until each part has one element – A single element is already sorted by definition – Then, pairs of sorted subarrays are merged to form bigger sorted arrays So: – First, size-1 arrays are merged into size-2 sorted arrays – Then size-2 into size-4 – Then size-4 into size-8 – And so on, until the whole array is sorted The key insight: 👉 All the real sorting happens during merging, not during splitting. Once you understand that: • recursion just breaks the problem into smaller pieces • merge logic ensures order • time complexity stays O(n log n) in all cases Merge Sort isn’t about simplicity — it’s about guaranteed performance and clean divide-and-conquer thinking. That’s what makes it a foundation algorithm for: ✔ large datasets ✔ external sorting ✔ stable sorting requirements #Java #MergeSort #DSA #Algorithms #DivideAndConquer #ProblemSolving #BackendEngineering
To view or add a comment, sign in
-
Day 24 – Search in Rotated Sorted Array Worked on searching a target in a rotated sorted array using modified Binary Search. Key Learnings: Identifying which half of the array is sorted Deciding the correct side to continue search Maintaining O(log n) efficiency #DSA #RotatedArray #BinarySearch #CodingPractice #Java
To view or add a comment, sign in
-
-
Solved Search in a Rotated Sorted Array — where the array isn’t fully sorted… but still searchable in O(log n). Key insight? At every step, one half is always sorted. Identify it → check target range → eliminate half. 🎯 This problem was a reminder that: Binary Search isn’t just a template — it’s about thinking in ranges. #DSA #BinarySearch #Java #Coding #ProblemSolving #LearningDaily
To view or add a comment, sign in
-
-
#Coding5 Q: Find the Missing Number in an Array (Java) Example: int[] arr = {0, 1, 3, 4}; Output → 2 I explored 3 different approaches: ✅ 1. Using Sum Formula (O(n)) int n = arr.length; int expectedSum = n * (n + 1) / 2; int actualSum = 0; for(int num : arr) { actualSum += num; } int missing = expectedSum - actualSum; ✅ 2. Using XOR (O(n), avoids overflow) int xor = 0; for(int i = 0; i <= arr.length; i++) { xor ^= i; } for(int num : arr) { xor ^= num; } int missing = xor; ✅ 3. Using Sorting (O(n log n)) Arrays.sort(arr); for(int i = 0; i < arr.length; i++) { if(arr[i] != i) { System.out.println(i); break; } } Key Learnings: Sum and XOR approaches are interview preferred XOR avoids integer overflow Sorting is easier to understand but less optimal Practicing DSA daily to strengthen problem-solving skills #DSA #Java #Arrays #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
📌 Spring Boot Annotation Series – Part 14 ✅ @Qualifier annotation The @Qualifier annotation is used to resolve confusion when multiple beans of the same type exist 👇 🔹 Why do we need @Qualifier? When there are multiple implementations of the same interface, Spring gets confused about which one to inject. 👉 That’s where @Qualifier helps. 🔹 Example Scenario public interface PaymentService { void pay(); } @Service("upiService") public class UpiPaymentService implements PaymentService { public void pay() { } } @Service("cardService") public class CardPaymentService implements PaymentService { public void pay() { } } @RestController public class PaymentController { @Autowired @Qualifier("upiService") private PaymentService paymentService; } 👉 Here we are clearly telling Spring to inject UpiPaymentService. 🔹 What happens without @Qualifier? ❌ Spring throws: NoUniqueBeanDefinitionException Because it finds more than one matching bean. 🔹 In simple words @Qualifier helps Spring choose the correct bean when multiple beans of the same type are available. 👉 🧠 Quick Understanding Used with @Autowired Resolves multiple bean conflict Avoids NoUniqueBeanDefinitionException Makes dependency injection clear #SpringBoot #Java #Qualifier #DependencyInjection #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development