🔹 Problem 1: Second Smallest Element in an Array 📌 Input: Integer n (size of array), Array of n elements 📌 Output: Second smallest element in the array 🧠 Algorithm Steps: 1. Read the array elements. 2. Assume first element as first_min and second element as second_min. 3. If first_min is greater than second_min, swap them. 4. Traverse the array from index 2. 5. If current element < first_min → second_min = first_min and first_min = current element. 6. Else if current element > first_min and < second_min → update second_min. 7. If both minimum values are equal, print "No second smallest element", otherwise print second_min. 💡 Example: Input: [5, 2, 8, 1, 3] Output: 2 🔹 Problem 2: First Non-Repeating Character in a String 📌 Input: String s 📌 Output: First character that appears only once 🧠 Algorithm Steps: 1. Read the string. 2. Traverse each character. 3. For each character, count its frequency using another loop. 4. If count == 1, print that character and stop. 5. If no such character found, print -1. 💡 Example: Input: "swiss" Output: w 🔹 Problem 3: Hashad Number 📌 Input: Integer n 📌 Output: Check whether the number is Hashad or not 🧠 Algorithm Steps: 1. Store original number. 2. Find sum of digits using loop. 3. Check if original number % sum == 0. 4. If true, print "Hashad Number". 5. Otherwise, print "Not Hashad Number". 💡 Example: Input: 18 Output: Hashad Number Consistent practice of these problems is helping me improve my logical thinking, loop handling, and core Java fundamentals. 🚀 #Java #CodingPractice #ProblemSolving #CoreJava #LearningJourney
Here are the three titles, each 50 characters or fewer, matching the original post's sentiment and including the most important named entity: 1. Java: Second Smallest Element in Array 2. Java: First Non-Repeating Character in String 3. Java: Check Hashad Number
More Relevant Posts
-
🚀 Day 9 of My DSA Journey Today I solved the “Reverse Integer” problem on LeetCode using Java. This problem focuses on number manipulation, loops, and handling integer overflow, which makes it slightly tricky compared to basic problems. 💡 Problem Overview We are given a signed 32-bit integer x, and the task is to reverse its digits. Example: Input: 123 → Output: 321 Input: -123 → Output: -321 However, there is an important condition: ⚠️ If reversing the number causes it to go outside the 32-bit integer range, we must return 0. The valid integer range is: −2³¹ to 2³¹ − 1 ⚙️ Approach I Used I solved this problem using mathematical digit extraction: 1️⃣ Extract the last digit using x % 10 2️⃣ Remove the last digit from the number using x / 10 3️⃣ Build the reversed number using sum = sum * 10 + digit 4️⃣ Before adding the digit, check overflow condition using Integer.MAX_VALUE and Integer.MIN_VALUE. 📊 Complexity Analysis Time Complexity: O(log₁₀ n) Because the number of digits in n determines the number of loop iterations. Space Complexity: O(1) No extra memory is used. 📚 Key Learnings ✔ Practiced digit manipulation using modulus and division ✔ Learned how to handle integer overflow conditions ✔ Strengthened understanding of mathematical logic in algorithms 💻 Result ✅ Accepted ⚡ Runtime: 1 ms (Beats 99.88%) Small progress every day is building a strong foundation in Data Structures and Algorithms. On to Day 10 tomorrow. 💪 #DSA #LeetCode #100DaysOfCode #Java #ProblemSolving #CodingJourney #LearningInPublic #SoftwareDevelopment #Consistency
To view or add a comment, sign in
-
-
🚀 Day 18 of My DSA Journey – Subarray Sum Equals K (Prefix Sum + HashMap) Today I solved the classic “Subarray Sum Equals K” problem using Prefix Sum and a HashMap in Java. 🔍 Problem Statement: Given an integer array and an integer k, return the total number of continuous subarrays whose sum equals k. 💡 Approach I Used: Instead of checking all subarrays (which would be O(n²)), I optimized it using: 1️⃣ Prefix Sum technique 2️⃣ HashMap to store frequency of prefix sums Core idea: If at any index: currentSum - k = previousPrefixSum Then there exists a subarray ending at the current index whose sum is k. So for every element: • Keep adding to running sum • Check if (sum - k) exists in the map • If yes → add its frequency to result • Update the map with current sum frequency I also initialized: map.put(0, 1) This handles cases where a subarray starting from index 0 itself equals k. --- 🎯 Key Learnings: ✅ Prefix Sum converts subarray problems from O(n²) → O(n) ✅ HashMap helps track past computations efficiently ✅ Understanding the math behind sum - k is crucial ✅ Always think: “Can I reuse previous computation?” Time Complexity: O(n) Space Complexity: O(n) Consistency + Pattern Recognition = Growth 📈 Day 18 complete ✔ On to the next challenge. #DSA #Java #PrefixSum #HashMap #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
Consistency is the secret sauce for placement preparation, and today focused on diving deeper into functional logic and mathematical computing in Java. Understanding these concepts goes beyond syntax; it's about optimizing our approach to solving complex problems. Here’s a breakdown of what I tackled today: 📑 Day 02/200: Deep Dive into Java Logic 1) Functions with Parameters: Mastered how to pass data into methods to enhance code modularity and reusability. 2) Factorial Logic: Implemented both iterative and recursive approaches to calculate n!. 3) Binomial Coefficient: Applied function call nesting to solve combinations using the formula. 4) Range Analysis: Explored data limits and how to manage constraints within loops. 5) Bit Conversion: Experienced the "aha!" moment of the day—converting numbers between Binary and Decimal systems. 💡 Key Takeaway The Binomial Coefficient problem reinforced the importance of using functions. Instead of writing the factorial loop multiple times, one well-defined function handled all the work, showcasing efficiency. Current Status: 02 / 200 Days Completed ✅ #PlacementPrep #JavaProgramming #CodingJourney #100DaysOfCode #EngineeringLife #ProblemSolving #SoftwareDevelopment github: https://lnkd.in/dT9Wd8Nq
To view or add a comment, sign in
-
-
✨ Good day.... Developers! Creating and traversing arrays is important… But how do we find an element inside an array? 🤔 That’s where Searching comes in 🔍 1️⃣ Linear Search (Sequential Search) 👉 Checks each element one by one 👉 Works on both sorted & unsorted arrays int[] arr = {10, 20, 30, 40}; int key = 30; for(int i = 0; i < arr.length; i++){ if(arr[i] == key){ System.out.println("Element found at index: " + i); break; } } ==> ⏱ Time Complexity: O(n) ✔ Simple ✔ Beginner-friendly ✔ No sorting required 2️⃣ Binary Search 👉 Works only on sorted arrays 👉 Divides the array into halves import java.util.Arrays; int[] arr = {10, 20, 30, 40, 50}; int key = 30; int index = Arrays.binarySearch(arr, key); System.out.println("Element found at index: " + index); ==> ⏱ Time Complexity: O(log n) ✔ Faster than linear search ✔ Requires sorted data 🔥 Interview Insight 📌 When array is small → Linear search is fine 📌 When array is large & sorted → Binary search is better 📌 Binary search on unsorted array → ❌ Wrong logic #Java #DSA #Programming #CodingInterview #LearningJourney #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Day 19 of My DSA Journey – Find All Anagrams in a String (Sliding Window + Frequency Array) Today I solved the “Find All Anagrams in a String” problem using the Sliding Window technique with character frequency arrays in Java. 🔍 Problem Statement: Given two strings s and p, return all starting indices of p’s anagrams in s. 💡 Approach I Used: 1️⃣ If p.length() > s.length(), return empty list immediately. 2️⃣ Create two frequency arrays of size 26: • need[] → stores frequency of characters in p • have[] → stores frequency of current window in s 3️⃣ Build the first window of size m. 4️⃣ Compare both frequency arrays. 5️⃣ Slide the window one character at a time: • Remove left character • Add right character • Compare again 6️⃣ If both arrays match → add starting index to result list. Instead of sorting every substring (which would be expensive), I used frequency comparison to keep the solution efficient. --- 🎯 Key Learnings: ✅ Sliding Window is extremely powerful for substring problems ✅ Frequency arrays help avoid repeated sorting ✅ Comparing fixed 26 characters keeps checks constant time ✅ Pattern recognition makes similar problems easier (Permutation in String helped here!) Time Complexity: O(n) Space Complexity: O(1) (excluding result list) Day 19 complete ✔ Consistency is building confidence every single day 💯 #DSA #Java #SlidingWindow #Anagrams #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 11 of #50DaysLeetCode Challenge Today I tackled a HARD problem: “Regular Expression Matching” on LeetCode using Java. 🔹 Problem: Given a string "s" and a pattern "p", implement regex matching with support for: • "." → matches any single character • "*" → matches zero or more of the preceding element Return true if the entire string matches the pattern. Example: Input: "s = "aa", p = "a*"" → Output: "true" Input: "s = "aa", p = "a"" → Output: "false" 🔹 Approach I Used: I used Dynamic Programming (DP) — anything else here is inefficient or breaks on edge cases. ✔ Created a 2D DP table "dp[m+1][n+1]" ✔ "dp[i][j]" represents whether "s[0...i-1]" matches "p[0...j-1]" ✔ Handled "*" carefully: - Treat it as zero occurrence → "dp[i][j-2]" - Or one/more occurrence → match previous character ✔ Built the solution bottom-up 🔹 Concepts Practiced: • Dynamic Programming (2D DP) • String pattern matching • Handling complex edge cases #LeetCode #DSA #Java #DynamicProgramming #Algorithms #CodingChallenge #50DaysOfCode
To view or add a comment, sign in
-
-
Day 49 Problem statement: You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers. The test cases are generated so that the answer fits in a 32-bits integer Example: For the tree [1,0,1,0,1,0,1] Paths formed: 100 → 4 101 → 5 110 → 6 111 → 7 Total = 22 Approach: While traversing the tree using DFS, we build the binary number step by step. At each node: val = 2 * val + root.val Why multiply by 2? Because in binary: Left shift = multiply by 2 Then add current bit This simulates constructing a binary number as we move down the tree. Approach: Use DFS (Preorder traversal) Carry the current binary value When we reach a leaf → return the computed number Sum left and right subtree results Java code class Solution { public int dfs(TreeNode root, int val){ if(root == null) return 0; val = 2 * val + root.val; if(root.left == null && root.right == null){ return val; } return dfs(root.left, val) + dfs(root.right, val); } public int sumRootToLeaf(TreeNode root) { return dfs(root, 0); } } #HappyCoding #DSA #Trees #LeetCode #DSA #BinaryTree #Algorithms #Java #ProblemSolving #CodingJourney #InterviewPreparation #SoftwareEngineering #CareerGrowth
To view or add a comment, sign in
-
🚀 Day 22 of #75DaysofLeetCode LeetCode Problem Solved: Determine if Two Strings Are Close (1657) Another interesting String + Frequency Analysis problem from LeetCode! 🔹 Problem: Two strings are considered close if we can transform one into the other using: 1️⃣ Swap any two characters (rearranging characters). 2️⃣ Transform all occurrences of one character into another existing character and vice versa. We need to determine whether word1 can be converted into word2 using these operations. 💡 Key Insights: To make two strings close, three conditions must hold: ✔️ Both strings must have the same length. ✔️ Both strings must contain the same set of characters. ✔️ The frequency distribution of characters must match after sorting. Why? Because operation 2 allows us to swap character frequencies between existing characters. 💻 Java Solution: import java.util.*; class Solution { public boolean closeStrings(String word1, String word2) { if(word1.length() != word2.length()) return false; int[] freq1 = new int[26]; int[] freq2 = new int[26]; for(char c : word1.toCharArray()) freq1[c - 'a']++; for(char c : word2.toCharArray()) freq2[c - 'a']++; for(int i = 0; i < 26; i++){ if((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) return false; } Arrays.sort(freq1); Arrays.sort(freq2); return Arrays.equals(freq1, freq2); } } 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Problems like this help strengthen understanding of hashing, frequency counting, and string manipulation, which are common in coding interviews. #LeetCode #DSA #Java #CodingPractice #Algorithms #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
After a long break spent in Holi and some family event. Back to posting the DSA updates. Day 20 ( DSA using Java) To strengthen my foundation in Data Structures and Algorithms, I’m committing to solving and sharing LeetCode problem in regular periods of time, along with my thought process and approach. Writing it out helps me learn better and opens the door to meaningful discussion. 🔹 Problem: palindrome LL,recursion 🔹 Core Concept: Linked list solution : class Solution { public ListNode middleNode(ListNode head) { ListNode fast = head; ListNode slow = head; while(fast != null && fast.next != null){ fast = fast.next.next; slow = slow.next; } return slow; } public ListNode revLL(ListNode head){ if(head == null){ return head; } ListNode previous = null; ListNode present = head; ListNode next = null; while (present != null) { next = present.next; present.next = previous; previous = present; present = next; } head = previous; return head; } public boolean isPalindrome(ListNode head) { ListNode mid = middleNode(head); ListNode h2 = revLL(mid); ListNode revHead = h2; ListNode first = head; while (h2 != null) { if(first.val != h2.val){ revLL(revHead); return false; } first = first.next; h2 = h2.next; } revLL(revHead); return true; } } I’ve included my solution and time–space complexity analysis. I’d love to hear how others approached this problem—were there alternative or more efficient strategies? Let’s learn, improve, and grow together. #LeetCode #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #LearningInPublic #Java
To view or add a comment, sign in
-
🚀Day - 24 | Day - 8: Deep Dive into Linked Lists! Today, my DSA journey took me beyond the basics of Arrays and into the flexible world of Linked Lists. While Arrays are great, I quickly realized they have their limits—specifically when it comes to memory and efficiency. 📉 The "Array" Problem Arrays require contiguous memory, which can be a pain to allocate for large datasets. Plus, inserting or deleting elements is expensive because you have to shift everything else around. 💡 The Solution: Linked Lists A Linked List is a collection of Nodes. Each node is like a small container with two parts: Data: The actual value you want to store. Next (Address): A pointer/reference to the next node in the sequence. The list starts with a Head and ends when a node points to Null. No more shifting elements! Just update the pointers, and you're good to go. 🛠️ What I Built Today I moved from theory to implementation using Java. Here’s a snapshot of what I practiced: Structure: Defined the Node using Classes and Objects. Traversal: Mastered the while loop to navigate the list (since we don't have indexes like Arrays). Core Operations: Adding elements (at the beginning, end, and specific indexes). Removing elements (first and last). Printing the entire list. 🧠 Key Takeaway If you need fast insertions and deletions without worrying about pre-allocating memory blocks, Linked Lists are best. A big thanks to Poovizhi Mam for the clear explanation and hands-on coding practice✨ #DSA #CodingJourney #Java #DataStructures #LinkedList #LearningInPublic #SoftwareEngineering
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