DSA Practice – Day 52 🚀 Problem: Happy Number (LeetCode 202) 📌 Problem Statement: A number is called happy if repeatedly replacing it with the sum of the squares of its digits eventually leads to 1. Return true if it’s a happy number, otherwise false. 🧩 Brute Force Approach: Keep track of all numbers seen in a set to detect loops. If you reach 1, Happy Number If a number repeats, Not Happy Time Complexity: O(log n) Space Complexity: O(log n) ⚡ Optimal Approach (Floyd’s Cycle Detection): Use two pointers — slow and fast. Move slow by one step and fast by two steps (using sum of squares). If they meet, there’s a cycle (not happy). If you reach 1, it’s a happy number. Time Complexity: O(log n) Space Complexity: O(1) ✨ What I Learned: How to detect cycles in number transformations. Applying Floyd’s cycle detection beyond linked lists. Improved logical problem-solving for number-based questions. #LeetCode #Java #ProblemSolving #DSA #CodingJourney #PlacementPrep
Happy Number Problem: Brute Force and Floyd's Cycle Detection
More Relevant Posts
-
⚙️ Day 38 of My LeetCode Journey — Problem #2654 “Minimum Number of Operations to Make All Array Elements Equal to 1” (Java Solution) 💡 Today’s challenge beautifully combined number theory with algorithmic optimization. The goal: turn every element in an array into 1 using the minimum operations — and the key insight was rooted in GCD properties. 🔍 My thought process: If any 1s exist → we just need to handle the rest (n - count(1)). Otherwise → find the shortest subarray with GCD = 1, since it’s the only way to generate a 1. The final answer = minimal window length + (n - 1) operations. It’s fascinating how understanding mathematical relationships can drastically simplify code complexity 🔢 Each problem reminds me — elegant logic is what turns code into art 🧠💻 #Day38 #LeetCode #Java #ProblemSolving #NumberTheory #Algorithms #DSA #CodingJourney #100DaysOfCode #CodeEveryday #SoftwareEngineering #LearningInPublic #TechCommunity
To view or add a comment, sign in
-
-
DSA Practice – Day 58 🚀 Problem: Linked List Cycle (LeetCode 141) Problem Statement: Given the head of a linked list, determine if the linked list has a cycle in it. A cycle exists if a node’s next pointer points to a previous node in the list. ⚡ Brute Force Approach: Use a HashSet to store visited nodes. While traversing the list: If a node is already in the set → cycle detected. Otherwise, add it to the set. If traversal ends (null reached) → no cycle. Time Complexity: O(n) Space Complexity: O(n) ⚡ Optimal Approach (Floyd’s Cycle Detection): Use two pointers — slow and fast. Move slow by one step and fast by two steps. If they meet → cycle exists. If fast or fast.next becomes null → no cycle. Time Complexity: O(n) Space Complexity: O(1) ✨ What I Learned: The Floyd’s Cycle Detection Algorithm is a clever way to find loops efficiently. Two-pointer techniques are extremely useful in linked list problems. #DSA #Java #LinkedList #FloydCycleDetection #ProblemSolving #LeetCode #CodingJourney #PlacementPrep
To view or add a comment, sign in
-
-
🔥 Day 111 of My DSA Challenge – Subsets II (Handling Duplicates) 🔷 Problem : 90. Subsets II 🔷 Goal : Generate all possible subsets of an array that may contain duplicates No duplicate subsets allowed 🔷 Key Insight : This is an extension of the classic Subsets / Power Set problem — but here the array can contain duplicates, so we must avoid repeating subsets. Core idea : At each element, you can : ✅ Include it ❌ Skip it But when skipping, you must skip all duplicates of that element at that step this ensures all generated subsets are unique. 🔷 Approach : 1️⃣ Sort the array to group duplicates 2️⃣ Use recursion + backtracking to try all possibilities 3️⃣ Skip duplicate values when they appear in the same decision branch Time Complexity: O(2ⁿ) Space Complexity: O(n) Subsets II builds the backtracking mindset further: When values repeat, skip duplicate branches — not decisions. This pattern is powerful for problems like : ✅ Combination Sum II ✅ Unique permutations ✅ Partitioning problems Little wins → Big breakthroughs Every problem improves logic and patience. On to the next one 👊🔥 #Day111 #100DaysOfCode #LeetCode #DSA #Java #Backtracking #Recursion #Subsets #PowerSet #CodingChallenge #Algorithms #ProblemSolving #DeveloperJourney
To view or add a comment, sign in
-
DSA Practice – Day 48 🚀 Problem: Sort Array by Parity(LeetCode 905) Problem Statement: Given an integer array nums, move all even integers to the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. ⚡ Brute Force Approach: Create a new array. First, add all even numbers from nums to it. Then, add all odd numbers. Return the new array. Time Complexity: O(n) Space Complexity: O(n) (because of the extra array) ⚡ Optimal Approach (Two Pointer Technique): Use two pointers — one at the start (left) and one at the end (right). If the left element is odd and the right is even, swap them. Move pointers accordingly until they meet. This sorts even and odd numbers in-place without extra space. Time Complexity: O(n) Space Complexity: O(1) ✨ What I Learned: How to use the two-pointer approach for in-place array rearrangement. Simple logic can drastically reduce space usage in problems like these. #DSA #LeetCode #Java #Arrays #TwoPointer #ProblemSolving #Coding #InterviewPrep
To view or add a comment, sign in
-
-
I’ve realized that DSA is not just about solving problems—it’s about how many you solve and how deeply you understand the underlying concepts. The more problems you practice, the easier it becomes to recognize patterns and apply the right approach. Today, I worked on LeetCode 1971 – Find if Path Exists in a Graph, marked as an Easy problem. But to solve it confidently, you actually need strong fundamentals in: 🔹 Graph theory 🔹 DFS & BFS (and when to use which) 🔹 Difference between Graphs vs Trees 🔹 Edge List vs Adjacency List 🔹 How to build an adjacency list in code 🔹 How DFS works internally on graphs After around two months of consistent practice, I’m finally able to identify the prerequisites required for each problem and approach them with a structured mindset. If you're exploring graphs, I highly recommend giving this problem a try. Here’s the problem: https://lnkd.in/g6hMyn88 And here’s my LeetCode profile if you'd like to connect or share feedback: https://lnkd.in/gp38YMN7 #LeetCode #DSA #Java #SoftwareEngineering #Graphs #Coding #LearningJourney
To view or add a comment, sign in
-
-
DSA Practice – Day 54 🚀 Problem: Maximum Product Subarray Problem Statement: Find the contiguous subarray within an array (containing at least one number) which has the largest product. ⚡ Brute Force Approach: Generate all possible subarrays. Calculate the product of each subarray. Keep track of the maximum product found. Time Complexity: O(n²) Space Complexity: O(1) ⚡ Optimal Approach (Prefix–Suffix Product): Maintain two running products — prefix (left to right) and suffix (right to left). Reset the product to 1 whenever it becomes 0. Keep updating the maximum product found so far. Time Complexity: O(n) Space Complexity: O(1) ✨ What I Learned: Prefix–suffix logic can simplify problems that seem complex initially. Resetting counters or products helps handle zeros effectively. Great way to practice array traversal from both ends! #LeetCode #Java #DSA #ProblemSolving #CodingJourney #PlacementPrep
To view or add a comment, sign in
-
📌 Day 51/100 – Longest Word in Dictionary (LeetCode 720) 🔹 Problem: Given an array of words, find the longest word that can be built one character at a time by other words in the array. If multiple results exist, return the lexicographically smallest one. 🔹 Approach: Built a Trie structure to store all words. Used DFS traversal to explore all valid prefixes (where every prefix forms a valid word). Updated the answer when a longer or lexicographically smaller valid word was found. 🔹 Key Learning: Deepened understanding of Trie traversal with DFS. Practiced combining lexicographical comparison with prefix validation. Reinforced prefix-based word-building logic efficiently. 🔹 Complexity: Time: O(N × L) — N = number of words, L = average word length Space: O(26 × N × L) — for Trie storage #Day51Of100 #LeetCode720 #100DaysOfCode #Java #DSA #Trie #DFS #ProblemSolving #CodingChallenge #Strings #DataStructures #CodingJourney #KeepLearning
To view or add a comment, sign in
-
-
🌟 Day 44 – LeetCode Practice Problem: Product of Array Except Self (LeetCode #238) 📌 Concept: Given an integer array, create a new array where each element equals the product of all other elements except itself, without using division. 🧠 My Approach: First pass → compute prefix products (multiply everything before current index) Second pass → compute suffix products (multiply everything after current index) Combine both to get the result for each index efficiently No extra multiplication array used — optimized and clean logic ⚡ This avoids division and runs in linear time — exactly what the problem demands ✅ 📈 Result: ✅ Accepted ⚡ Runtime: 2 ms (Beats ~87%) 📦 Memory: Efficient usage 💡 Key Learning: This problem reinforces the power of prefix & suffix computation — a common trick in array manipulation + interview favorite. Great way to improve problem-solving without relying on brute force or division. --- 🚀 Growing stronger every day in DSA! #LeetCode #DSA #Java #ProblemSolving #PrefixSuffix #CodingJourney #ArrayProblems #LearningMindset
To view or add a comment, sign in
-
-
✅Day 54 : Leetcode 3228 - Maximum Number of Operations to Move Ones to the End #60DayOfLeetcodeChallenge 🧩 Problem Statement You are given a binary string s. You can perform the following operation any number of times: Choose an index i such that: i + 1 < s.length s[i] == '1' s[i+1] == '0' Then move this '1' to the right until it reaches the next '1' or the end of the string. Your task is to return the maximum number of such operations that can be performed. ✅ My Approach Instead of simulating every movement (which is slow), I used a counting strategy: 🔹 Key Idea Whenever I see a '1', I increase the count of ones seen so far. Whenever I see a pattern like …10…, this '1' can move past all previous ones, contributing extra operations equal to the number of '1's before it. 🔹 Steps Initialize: ones = 0 → counts how many '1' encountered so far. res = 0 → stores total operations. Traverse the string: If current char is '1' → increment ones. Else if the previous char is '1' (meaning we found 10) → add ones to result. Return res as the maximum operations. This avoids simulation and gives the optimal count directly. ⏱ Time Complexity O(n) — Single scan through the string O(1) space #dsa #leetcode #binarysearch #java #coding #problemsolving #100daysofdsa #interviewpreparation #learningeveryday #codingjourney
To view or add a comment, sign in
-
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