#Coding2 Q: Find the second largest element in an array. Example: int[] arr = {1, 34, 56, 78, 90}; Output → 78 I explored 3 different approaches: ✅ 1. Single Pass (Optimal – O(n)) int largest = Integer.MIN_VALUE; int secondLargest = Integer.MIN_VALUE; for(int num : arr) { if(num > largest) { secondLargest = largest; largest = num; } else if(num > secondLargest && num != largest) { secondLargest = num; } } ✅ 2. Using Sorting (O(n log n)) Arrays.sort(arr); int secondLargest = arr[arr.length - 2]; ✅ 3. Using Java Streams int secondLargest = Arrays.stream(arr) .boxed() .sorted(Collections.reverseOrder()) .distinct() .skip(1) .findFirst() .get(); Key Learnings: Single-pass approach is interview preferred (O(n) time, O(1) space) Handle duplicates carefully Streams and sorting are cleaner but less optimal. Practicing fundamentals daily to strengthen problem-solving skills #DSA #Java #ProblemSolving #CodingJourney #InterviewPrep #SoftwareEngineer #LearningInPublic #LinkedInDSA
Find Second Largest Element in Array: 3 Approaches
More Relevant Posts
-
#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
-
#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
-
𝐖𝐞𝐞𝐤 2 | 𝐃𝐚𝐲 6/7 — 𝐃𝐒𝐀 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞 Today, I practiced generating 𝐮𝐧𝐢𝐪𝐮𝐞 𝐩𝐞𝐫𝐦𝐮𝐭𝐚𝐭𝐢𝐨𝐧𝐬 𝐨𝐟 𝐚𝐧 𝐚𝐫𝐫𝐚𝐲 containing duplicate elements using Java Backtracking. 𝐊𝐞𝐲 𝐇𝐢𝐠𝐡𝐥𝐢𝐠𝐡𝐭𝐬: • Implemented backtracking with recursion to explore all arrangements • Sorted the array to handle duplicate elements efficiently • Used a boolean tracking array to manage element usage • Applied duplicate-skipping logic to ensure only unique permutations • Strengthened understanding of recursion trees and state tracking This challenge improved my ability to handle duplicate constraints in combinatorial problems, an important concept for technical interviews and real-world algorithm design. #Day6Of7DaysOfCode #DSA #Java #Backtracking #Recursion #ProblemSolving #CodingChallenge #InterviewPrep #Algorithms
To view or add a comment, sign in
-
-
Today I revisited the Combination Sum problem using Java and backtracking. The key takeaway wasn’t recursion itself — it was writing precise base conditions and managing state correctly. A small mistake in boundary handling or list references can completely change the output. Backtracking reinforces an important principle in software engineering: Clear logic > Complex logic. Continuously improving problem-solving depth, one recursion at a time. #Java #DSA #Backtracking #ProblemSolving #SoftwareEngineering #CodingInterview
To view or add a comment, sign in
-
-
🔗 DSA Practice — Merge Two Sorted Lists (Recursive Approach) Today I solved LeetCode 21: Merge Two Sorted Lists using the recursive approach, which offers a very clean and intuitive solution for linked list merging. 🔍 Key Learnings Recursion helps naturally express the merge logic. At each step, choose the smaller node and recurse on the rest. Base cases are critical to prevent unnecessary recursion. Elegant solutions often come from thinking recursively. 🧠 Why This Problem Matters One of the most common linked list interview problems. Strengthens understanding of recursion with pointers. Builds confidence in writing clean, readable code. 📌 Final Takeaway This problem shows that recursion isn’t just a concept — it can lead to simpler and more expressive solutions when used correctly. #leetcode #dsa #linkedlist #recursion #problemSolving #codingpractice #java #interviewpreparation #datastructures #100DaysOfCode #softwareengineering
To view or add a comment, sign in
-
-
#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
-
Day38 - LeetCode Journey Solved LeetCode 434: Number of Segments in a String using Java ✅ Simple problem, sharp thinking. This one reinforces how much attention to detail matters in string-based questions. Instead of relying on split methods, scanning the string and detecting valid word boundaries made the solution both clean and efficient. What stood out today was handling edge cases like extra spaces and string boundaries correctly. Small logic, big clarity. Key takeaways: • Stronger understanding of string traversal • Better handling of edge cases • Writing efficient, single-pass solutions • Building solid fundamentals for interviews Progress isn’t always loud. Sometimes it’s these small wins that build real confidence. On to the next 🚀 #LeetCode #DSA #Java #StringManipulation #ProblemSolving #Algorithms #CodingJourney #InterviewPrep #Consistency #DailyPractice
To view or add a comment, sign in
-
-
🚀 Day 26/30 – Longest Common Subsequence (LCS) Today’s problem was a classic Dynamic Programming challenge that appears frequently in coding interviews and forms the foundation for many string comparison problems. 🧠 Problem Insight Given two strings, the goal is to determine the length of the longest subsequence that appears in both. A subsequence: Maintains order Does not need to be contiguous This makes it different from substring problems and requires a smarter approach than brute force. ⚙️ Approach I implemented a 2D Dynamic Programming solution: dp[i][j] → stores the LCS length for first i characters of text1 and first j characters of text2 Transition Logic: If characters match: dp[i][j] = 1 + dp[i-1][j-1] If they don’t match: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) This builds the solution bottom-up by reusing previously solved subproblems. ⏱ Complexity Time Complexity: O(n × m) Space Complexity: O(n × m) 📊 Performance ✅ All test cases passed ⚡ Beats ~99% in runtime 🧩 Key Pattern Learned This problem is the base template for: ✔ Edit Distance ✔ Shortest Common Supersequence ✔ Diff tools / Version control algorithms ✔ Sequence matching problems Understanding LCS makes many advanced DP string problems much easier. 🎯 Interview Takeaway Instead of thinking in terms of matching full strings, I learned to think in terms of: “What is the best answer using smaller prefixes of both strings?” That shift in perspective is the real DP skill. 📈 Growth Reflection Dynamic Programming on strings now feels much more structured — recognizing overlapping subproblems and converting them into table form is becoming natural. Consistency is turning complex patterns into repeatable logic 💪 ✅ Day 26 completed. #Day26 #30DaysOfCode #LeetCode #DynamicProgramming #LCS #StringDP #Java #InterviewPreparation #ProblemSolving #TechGrowth
To view or add a comment, sign in
-
-
𝗠𝗼𝘀𝘁 𝗗𝗦𝗔 𝗽𝗿𝗼𝗯𝗹𝗲𝗺𝘀 𝗯𝗲𝗰𝗼𝗺𝗲 𝗰𝗼𝗺𝗽𝗹𝗲𝘅 𝗯𝗲𝗰𝗮𝘂𝘀𝗲 𝘄𝗲 𝘁𝗿𝘆 𝘁𝗼 𝘀𝗼𝗹𝘃𝗲 𝗲𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴 𝗮𝘁 𝗼𝗻𝗰𝗲. 𝗗𝗮𝘆 𝟲/𝟯𝟬 – DSA Pattern: Recursion 🧠 How to spot this pattern If the problem: • Repeats the same logic on smaller input • Can be divided into identical subproblems • Has a clear stopping condition • Works naturally on trees or choices 👉 Think Recursion 💡 𝗦𝗶𝗺𝗽𝗹𝗲 𝗶𝗱𝗲𝗮 Instead of solving the full problem: • Solve one small part • Delegate the rest to the same function • Stop when input becomes simple The base case decides when to stop. ✏️ Pseudocode 𝙨𝙤𝙡𝙫𝙚(𝙭): 𝙞𝙛 𝙭 𝙞𝙨 𝙨𝙢𝙖𝙡𝙡: 𝙧𝙚𝙩𝙪𝙧𝙣 𝙧𝙚𝙨𝙪𝙡𝙩 𝙧𝙚𝙩𝙪𝙧𝙣 𝙨𝙤𝙡𝙫𝙚(𝙨𝙢𝙖𝙡𝙡𝙚𝙧 𝙭) 🧩 Problems that use this • Tree and graph DFS • Subsets and permutations • Backtracking problems • Divide & conquer algorithms 🔥 One rule to remember If the problem for size n depends on the same problem for size n-1, use Recursion. Recursion turns: ❌ solving everything together into ✅ solving one level at a time Tomorrow: Merge Intervals 👍 if this helped Comment “DSA” to follow the 30-day pattern series. #DSA #ProblemSolving #Java #CodingInterviews #LearningInPublic #30DaysOfDSA
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
Explore related topics
- Approaches to Array Problem Solving for Coding Interviews
- Java Coding Interview Best Practices
- Tips for Coding Interview Preparation
- Prioritizing Problem-Solving Skills in Coding Interviews
- Problem Solving Techniques for Developers
- Common Algorithms for Coding Interviews
- Solving Sorted Array Coding Challenges
- How to Use Arrays in Software Development
- How to Improve Array Iteration Performance in Code
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