🚀 Day 43 of #100DaysOfCode – LeetCode Problem #2460: Apply Operations to an Array 💬 Problem Summary: You’re given a non-negative integer array nums. You need to: Sequentially check each element nums[i]. If nums[i] == nums[i + 1], then: Multiply nums[i] by 2 Set nums[i + 1] to 0 After all operations, move all zeros to the end of the array. Return the resulting array. 🧩 Example: Input: [1,2,2,1,1,0] Output: [1,4,2,0,0,0] Explanation: - i=1: 2 == 2 → [1,4,0,1,1,0] - i=3: 1 == 1 → [1,4,0,2,0,0] Shift zeros → [1,4,2,0,0,0] 🧠 Logic: ✅ Traverse the array once, applying the doubling rule. ✅ Use a two-pointer approach or list building to shift zeros efficiently. 💻 Java Solution: class Solution { public int[] applyOperations(int[] nums) { int n = nums.length; for (int i = 0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } int index = 0; for (int num : nums) { if (num != 0) nums[index++] = num; } while (index < n) { nums[index++] = 0; } return nums; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: This problem reinforces the importance of in-place transformations and efficient data movement.
"LeetCode Problem #2460: Array Operations and Zero Shifting"
More Relevant Posts
-
🚀 Day 42 of #100DaysOfCode – LeetCode Problem #1356: Sort Integers by The Number of 1 Bits 💬 Problem Summary: Given an integer array arr, sort the integers in ascending order by the number of 1’s in their binary representation. If two or more integers have the same number of 1’s, sort them in ascending numerical order. 🧩 Example: Input: arr = [0,1,2,3,4,5,6,7,8] Output: [0,1,2,4,8,3,5,6,7] Explanation: 0 -> 0 bits 1,2,4,8 -> 1 bit 3,5,6 -> 2 bits 7 -> 3 bits 🧠 Logic: ✅ Count the number of 1s in each number’s binary form. ✅ Sort by (1) number of 1s, then (2) value. 💡 Key trick: Use the bit manipulation technique num &= (num - 1) to count set bits efficiently. 💻 Java Solution: class Solution { public int[] sortByBits(int[] arr) { Arrays.sort(arr, (a, b) -> { int countA = countBits(a); int countB = countBits(b); if (countA == countB) return a - b; return countA - countB; }); return arr; } private int countBits(int num) { int count = 0; while (num > 0) { num &= (num - 1); count++; } return count; } } ⚙️ Complexity: Time: O(n log n) (due to sorting) Space: O(1) ✅ Result: Accepted (Runtime: 1 ms) 💬 Takeaway: This problem beautifully combines sorting logic with bitwise manipulation. It’s a reminder that knowing how data is represented at the binary level gives you powerful optimization tools
To view or add a comment, sign in
-
🚀 Day 40 of #100DaysOfCode – LeetCode Problem #905: Sort Array By Parity 💡 Problem Summary: Given an integer array nums, move all even numbers to the front and all odd numbers to the back — return any valid ordering that satisfies this rule. 📘 Examples: Input: nums = [3,1,2,4] Output: [2,4,3,1] Explanation: Other valid answers include [4,2,3,1], [2,4,1,3]. 🧠 Approach: Create a new list to store results. First, add all even numbers. Then, add all odd numbers. Convert the list back to an array and return it. 💻 Java Solution: class Solution { public int[] sortArrayByParity(int[] nums) { List<Integer> arr = new ArrayList<>(); for (int num : nums) { if (num % 2 == 0) arr.add(num); } for (int num : nums) { if (num % 2 != 0) arr.add(num); } int[] array = new int[arr.size()]; for (int i = 0; i < arr.size(); i++) { array[i] = arr.get(i); } return array; } } ⚙️ Complexity: Time: O(n) Space: O(n) ✅ Result: Accepted (Runtime: 0 ms) 🎯 Key Takeaway: Sometimes, a problem doesn’t need a complex algorithm — just logical iteration and clean organization of data. Simple can still be powerful.
To view or add a comment, sign in
-
Design Decision: String vs Map<String, Object> vs JsonNode in Java Data Models ——————————————————————— When designing an entity or DTO that includes flexible JSON data — such as API metadata, configuration, or custom attributes — choosing the right data type can simplify (or complicate) your processing logic. Let’s compare: 1. String ———————————— private String metadata; • ✅ Best for raw storage (e.g., DB column). • ⚠️ Requires parsing when accessing JSON fields: JsonNode node = objectMapper.readTree(metadata); • 💡 Use this when the application doesn’t need to inspect the JSON frequently. 2. Map<String, Object> ———————————— private Map<String, Object> metadata; • ✅ Directly deserializable from JSON. • ✅ Easy to serialize back. • ⚠️ Type erasure at runtime — nested values might still need casting. • 💡 Good middle ground for APIs with predictable JSON structure. 3. JsonNode ———————————— private JsonNode metadata; • ✅ Tree model — allows partial traversal, dynamic keys, and on-demand access. • ✅ Integrates seamlessly with Jackson. • ⚠️ Slightly more verbose but powerful for schema-less payloads. String userType = metadata.path("user").path("type").asText(); Practical Scenario: ———————————- a. Raw storage or simple logging——> String b. Known structure but variable values ——> Map<String, Object> c. Highly dynamic / unknown schema ——> JsonNode #java #springboot #json #objectmapping #datamodel #jackson #backenddevelopment #softwaredesign #javadeveloper #api #restapi #microservices #codingtips #programming #softwareengineering #techinsights
To view or add a comment, sign in
-
💻✨ 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝟰𝟵𝟲 | 𝗡𝗲𝘅𝘁 𝗚𝗿𝗲𝗮𝘁𝗲𝗿 𝗘𝗹𝗲𝗺𝗲𝗻𝘁 𝗜 ✨💻 Today I worked on an interesting challenge — “Next Greater Element I”, a problem that tests both logical reasoning and data structure efficiency 🔍 🔹 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 (𝗦𝗶𝗺𝗽𝗹𝗶𝗳𝗶𝗲𝗱): Given two arrays nums1 and nums2, for each element in nums1, find the first greater element to its right in nums2. If no such element exists ➜ return -1. 🔹 𝗞𝗲𝘆 𝗖𝗼𝗻𝗰𝗲𝗽𝘁𝘀 𝗨𝘀𝗲𝗱: ✅ Stack (for tracking next greater efficiently) ✅ HashMap (for constant-time lookup) ✅ Reverse traversal → O(n) time 🔹 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Instead of using a brute-force O(n²) method, I used a monotonic decreasing stack, a powerful pattern for such problems — improving efficiency from O(n²) ➜ O(n) 🚀 Here’s a glimpse of my Java solution 👇 Stack<Integer> st = new Stack<>(); for (int i = n - 1; i >= 0; i--) { while (!st.isEmpty() && nums2[i] >= st.peek()) st.pop(); nge[i] = st.isEmpty() ? -1 : st.peek(); st.push(nums2[i]); } 🧠 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Choosing the right data structure can turn a complex problem into an elegant one. Always enjoy challenges that combine algorithmic thinking + clean code design 💡 #𝗝𝗮𝘃𝗮 #𝗖𝗼𝗱𝗶𝗻𝗴 #𝗗𝗦𝗔 #𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 #𝗣𝗿𝗼𝗯𝗹𝗲𝗺𝗦𝗼𝗹𝘃𝗶𝗻𝗴 #𝗦𝗼𝗳𝘁𝘄𝗮𝗿𝗲𝗘𝗻𝗴𝗶𝗻𝗲𝗲𝗿𝗶𝗻𝗴 #𝗛𝗶𝗿𝗶𝗻𝗴 #𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴
To view or add a comment, sign in
-
🚀 Day 38 of #100DaysOfCode – LeetCode Problem #747: Largest Number At Least Twice of Others 💡 Problem Summary: Given an integer array nums, find whether the largest number is at least twice as large as all other numbers. If it is, return the index of the largest element; otherwise, return -1. 📘 Example: Input: nums = [3,6,1,0] Output: 1 Input: nums = [1,2,3,4] Output: -1 🧠 Approach: Find the largest and second largest numbers in the array. If largest >= 2 * secondLargest, return the index of the largest. Otherwise, return -1. 💻 Java Solution: class Solution { public int dominantIndex(int[] nums) { int max = -1, second = -1, index = -1; for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { second = max; max = nums[i]; index = i; } else if (nums[i] > second) { second = nums[i]; } } return second * 2 <= max ? index : -1; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 🎯 Key Takeaway: Sometimes, solving problems isn’t about complex algorithms — it’s about thinking clearly and tracking key elements efficiently.
To view or add a comment, sign in
-
💡 When Lazy Loading Turns Into a Lazy Problem 😅 Lazy loading is amazing — until it bites you in legacy code. One of my entities had a field marked as LAZY, which made sense for performance. But in a few old methods (that weren’t inside a @Transactional context), I suddenly needed that field. Moreover, when you have a list of entities, manually initializing each lazy property quickly turns into a mess of boilerplate and open session errors. 😩 So, I went with a cleaner approach 👇 I kept two repository methods — one for lazy fetch, one for eager fetch using @EntityGraph (fetches the relation eagerly only when I really need it). No more manual initialization— just clean, purpose-driven queries. A single query to fetch all the data rather than executing query for each entity. Another note: Always try these things yourself — don’t ask AI about Hibernate’s internal queries or performance. It’ll hallucinate and give you the wrong answer with full confidence. The deeper you go, the more schizophrenic your AI becomes 😄 Have you tried a better solution for this kind of scenario? #Java #SpringBoot #Hibernate #SoftwareEngineering #TechLeadership #DeveloperTips
To view or add a comment, sign in
-
-
🚀 **JSON: The Developer's Swiss Army Knife** From REST APIs to config files and database exports, JSON is the universal language of data exchange. As devs, mastering JSON parsing, manipulation, and generation is non-negotiable. 💡 **Why it matters:** - Simplifies data handling across platforms - Powers modern web services and tools - Essential for seamless integrations Whether you're tweaking configs or building APIs, JSON fluency keeps you agile. Time to level up your JSON game! #JSON #WebDevelopment #APIs #DeveloperTools #DataExchange
To view or add a comment, sign in
-
✨ Today marks Day 7 of my LeetCode streak! I solved a fun and logical problem that reminded me how important simple ideas like arrays and booleans can be in solving tricky questions. 💡 Problem: Find the Two Sneaky Numbers In the town of Digitville, there’s a list called nums that should contain all integers from 0 to n - 1 exactly once. But two numbers decided to appear twice, making the list longer! 😅 My task was to find those two sneaky numbers and bring peace back to Digitville. 📘 Example: Input: nums = [0,3,2,1,3,2] Output: [2,3] Explanation: Numbers 2 and 3 appear twice in the array. 🧠 My Thought Process: At first, I thought of sorting the array and checking adjacent elements, but that would take O(n log n) time. Then I realized I could just keep track of which numbers I’ve seen using a boolean array — whenever I see a number again, that’s one of the sneaky ones! Since n ≤ 100, a simple O(n) solution works perfectly here. 💻 Code (Java): class Solution { public int[] getSneakyNumbers(int[] nums) { int n = nums.length - 2; boolean[] seen = new boolean[n]; int[] result = new int[2]; int idx = 0; for (int num : nums) { if (seen[num]) { result[idx++] = num; if (idx == 2) break; } else { seen[num] = true; } } return result; } } 🔍 Dry Run Example: nums = [0,3,2,1,3,2] Start → seen = [F,F,F,F] See 0 → mark as true See 3 → mark as true See 2 → mark as true See 1 → mark as true See 3 again → duplicate #1 See 2 again → duplicate #2 ✅ Output → [3,2] (order doesn’t matter) ⚙️ Complexity: Time: O(n) Space: O(n) Simple, clean, and efficient! 🎯 Key Learnings: Reinforced how boolean arrays can efficiently handle duplicates. Learned to identify when sorting isn’t needed — sometimes direct logic is faster. Keeping things simple often gives the most elegant solutions. 🗓️ LeetCode Streak: Day 7 / Small Steps → Big Progress 🚀 Each day I’m learning new ways to look at problems — this one taught me simplicity is power 💪 #LeetCode #100DaysOfCode #Java #DSA #ProblemSolving #LearningJourney #CodingPractice #DeveloperLife
To view or add a comment, sign in
-
-
LeetCode 104 – Maximum Depth of a Binary Tree 🌳 Today I solved one of the classic problems in data structures: “Given the root of a binary tree, return its maximum depth.” 👉 What’s a binary tree? A binary tree is a hierarchical structure where each node has at most two children: left and right. The maximum depth is simply the longest path from the root down to the farthest leaf. 🧩 Why Recursion Works Best Trees are naturally recursive: Each node is itself the root of a smaller subtree. To solve the whole tree, you solve the left subtree and the right subtree, then combine results. This makes recursion elegant and intuitive compared to iterative approaches. ✅ My Solution public int maxDepth(TreeNode root) { if (root == null) return 0; int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); return 1 + Math.max(leftDepth, rightDepth); } 📊 Complexity Time: O(n) → we visit every node once. Space: O(h) → recursion stack depends on tree height. Worst case (skewed tree): O(n) Best case (balanced tree): O(log n) 🎯 Key Takeaway Binary trees are a perfect example of why recursion is powerful. Once you “think recursively,” problems like maximum depth become straightforward. This problem reminded me that elegance in code often comes from matching the solution to the structure of the data. #LeetCode #DataStructures #BinaryTree #Recursion #Java #CodingJourney
To view or add a comment, sign in
-
-
When an event triggers your function, Lambda does not just run your code. Firstly, it creates a secure, isolated execution environment which serves as your function's temporary home. Lambda uses your configurations (memory, timeout, etc.) to optimise this setup, and this whole process is neatly split into three phases: Init, Invoke, and Shutdown. 🔹Phase 1: Initialisation(INIT) This is where the journey begin (expect the dreaded "cold start" for the first request). Lambda creates or "unfreezes" a secure execution environment, downloads your function's code, and any layers it needs. → Extension Init: Any companion extensions like monitoring or security agents get started first. They run their setup tasks, ensuring the full ecosystem is ready. → Runtime Init: The runtime (e.g., Node.js, Python, Java) is bootstrapped. It is the engine that will eventually execute your code. → Function Init: Finally, your function's static code is ran. Anything outside the main handler method is executed. This is where the heavy lifting like initializing SDK clients or creating database connections once and saving crucial milliseconds on subsequent calls is done. This meticulous initialisation ensures everything is perfectly set up before your core logic starts. 🔹Phase 2: Invocation(Invoke) → Function Call: Lambda invokes your function's handler method with the event data. → Execution: Your code runs its intended purpose which can be processing data, calling APIs, or whatever business logic it holds. → The Wait: Once your function completes, Lambda doesn't immediately scrap the environment. Instead, it freezes the environment, keeping it "warm" and ready. If another request for the same function arrives shortly, it skips the entire Init phase and jumps right back into Invoke, providing near-instantaneous response times and better performance. 🔹Phase 3: Shutdown When the execution environment sits idle, receiving no further requests for a period (the exact duration is up to AWS), the shutdown phase is initiated. → Runtime Shutdown: Lambda gracefully shuts down the function runtime. → Extension Shutdown: It alerts any running extensions and sends them a final shutdown event, giving them a brief window (typically up to two seconds) to stop cleanly, wrap up logs, or remove any remaining data before the environment is permanently terminated. 📌 Understanding this three-phased Execution lifecycle is key to writing high-performance, cost-efficient Lambda functions. ❓Is it just me who is always looking for what happens behind the scenes of every cloud service that I use or there is someone else that is interested in the little very little details?
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