#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
Karwan Vishweshwar’s Post
More Relevant Posts
-
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
-
-
🚀 Day 1/30 – Two Pointers Pattern Problem: Check if a String is Palindrome. Approach: Used two pointers (start & end) Compared characters from both ends Moved pointers inward after each comparison #Java #DSA #TwoPointers #CodingChallenge #BackendDeveloper public class CheckStringIsPolyndrome { public static void main(String[] args) { // check given string is palindrome String word = "abcd"; boolean result = isPolyndrome(word); if (result) { System.out.println("Palindrome"); } else { System.out.println("Not Palindrome"); } } private static boolean isPolyndrome(String word) { char[] charArray = word.toCharArray(); int start = 0, end = charArray.length - 1; while (end > start) { if (charArray[start] != charArray[end]) { return false; } start++; end--; } return true; } }
To view or add a comment, sign in
-
🔎Java String Program - Find Duplicate Characters in a String. Problem Statement: 👉 Input → "AabrbyzbCzucd"; 👉 Output →a : 2 times b : 3 times c : 2 times z : 2 times 🧠 Approach I followed: 1. First, we check whether the string is empty or null. 2. Convert the string into lowercase so 'A' and 'a' are treated the same. 3. Create an array of size 26 to store the count of characters from 'a' to 'z'. 4. For each character in the string: a). Find its position using (ch-97) or (ch - 'a') b). Increase its frequency in the array 5. Finally, print characters whose frequency is greater than 1 → these are duplicate characters: 📃 Implementation: //method to find Duplicate character public static void duplicateChar(String str) { if (str == null || str.isEmpty()) { System.out.println("String is empty"); return; } String lowerStr = str.toLowerCase(); // Converts string to lowercase int[] freqArray = new int[26]; for (int i = 0; i < lowerStr.length(); i++) { // Count frequency char ch = lowerStr.charAt(i); if (ch >= 97 && ch <= 122) { freqArray[ch - 97]++; } } System.out.println("Times of Duplicate Characters :=> "); for (int i = 0; i < freqArray.length; i++) { if (freqArray[i] > 1) { System.out.println((char) (i + 97) + ":" + freqArray[i] + " times"); } } } ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) (fixed array size) This problem improves: ✔ String handling ✔ Array logic ✔ Interview problem-solving approach #Java #CodingPractice #InterviewPreparation #Programming #DataStructures #JavaPractice #JavaDeveloper #BackedDeveloper #programming #learningJourney #interviewPreparation
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
-
#Coding10 👉 Q: Remove Duplicates from a Sorted Array (Two Pointer Technique – Java). Example: int[] arr = {1, 1, 2, 2, 3, 4, 4}; Output → {1, 2, 3, 4} Count → 4 ✅ Two Pointer Technique (Optimal – O(n), O(1)) static int removeDuplicates(int[] arr) { if(arr.length == 0) return 0; int j = 1; // pointer for next unique position for(int i = 1; i < arr.length; i++) { if(arr[i] != arr[i - 1]) { arr[j] = arr[i]; j++; } } return j; // number of unique elements } How It Works Since the array is already sorted, duplicates are adjacent i scans the array j tracks the position to place the next unique element When a new element is found → place it at index j Complexity Analysis • Time Complexity → O(n) • Space Complexity → O(1) (In-place solution) Two-pointer pattern is extremely powerful for array problems. #DSA #Java #Arrays #TwoPointers #ProblemSolving #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
#Coding9 Q: Reverse an Array Using Two Pointer Technique (Java) Example: int[] arr = {1, 2, 3, 4, 5}; Output → {5, 4, 3, 2, 1} ✅ Two Pointer Technique (Optimal Approach) static void reverse(int[] arr) { int left = 0; int right = arr.length - 1; while(left < right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } Approach Explanation: Start one pointer at the beginning (left) Start another pointer at the end (right) Swap both elements Move pointers toward the center Stop when they cross Complexity Analysis: • Time Complexity → O(n) • Space Complexity → O(1) (In-place solution) This approach is interview-preferred because it is simple, efficient, and uses no extra memory. #DSA #Java #Arrays #TwoPointers #ProblemSolving #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
#Coding9 Q: Move Zeros to the End (Two Pointer Technique – Java) Example: int[] arr = {0, 1, 0, 3, 12}; Output → {1, 3, 12, 0, 0} ✅ Two Pointer Technique (Optimal – O(n), O(1)) static void moveZeros(int[] arr) { int j = 0; // position to place next non-zero for(int i = 0; i < arr.length; i++) { if(arr[i] != 0) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; j++; } } } How It Works i scans the entire array j tracks where the next non-zero should go When a non-zero is found → swap with index j Zeros automatically move toward the end Complexity Analysis • Time Complexity → O(n) • Space Complexity → O(1) (In-place solution) This approach is interview-preferred because it is efficient and preserves order. #DSA #Java #Arrays #TwoPointers #ProblemSolving #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
-
𝐀𝐬 𝐝𝐞𝐯𝐞𝐥𝐨𝐩𝐞𝐫𝐬, 𝐰𝐞 𝐝𝐨𝐧’𝐭 𝐣𝐮𝐬𝐭 𝐰𝐫𝐢𝐭𝐞 𝐜𝐨𝐝𝐞. 𝐖𝐞 𝐦𝐮𝐬𝐭 𝐮𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝 𝐰𝐡𝐚𝐭 𝐡𝐚𝐩𝐩𝐞𝐧𝐬 𝐛𝐞𝐡𝐢𝐧𝐝 𝐭𝐡𝐞 𝐬𝐜𝐞𝐧𝐞𝐬. == vs .equals() in Java. At first glance, they look similar. But they check completely different things. == ------->Compares references (memory location) .equals() ----->Compares actual content Example: String s1 = "Java"; String s2 = "Java"; String s3 = new String("Java"); System.out.println(s1 == s2); // true System.out.println(s1 == s3); // false System.out.println(s1.equals(s3)); // true Why? ✔ s1 and s2 point to the same object in the String Constant Pool ✔ s3 creates a new object in the heap ✔ .equals() checks character-by-character content(not the reference) This small difference can cause BIG bugs, especially when working with Strings, Objects, or Collections. Understanding memory behavior > Memorizing syntax. #Java #Programming #LearningInPublic #dailyChallenge
To view or add a comment, sign in
-
𝗗𝗮𝘆 𝟮𝟬/𝟮𝟬 — 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 Solved 3Sum using Sorting + Two Pointer technique. ➤ Approach (O(n²), O(1) extra space apart from result): • First, sort the array • Fix one element i • Use two pointers (left, right) to find pairs such that --> nums[i] + nums[left] + nums[right] == 0 • Move pointers based on whether the sum is smaller or larger than zero • Store unique triplets ➤ Key Insight: Sorting simplifies the problem. Once sorted, the two-pointer technique efficiently avoids checking every combination. Brute force would be O(n³). Optimized approach reduces it to O(n²). #LeetCode #Java #DSA #TwoPointers #Sorting #ProblemSolving #20DaysChallenge #Consistency
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