Learned this sorting pattern today. When arranging numbers to form the largest possible number, normal sorting doesn't work. Example: [3, 30, 34, 5, 9] → "9534330" The pattern: [3, 30, 34, 5, 9] .map(String) .sort((a, b) => (b + a) - (a + b)) .join("") How it's different: Regular sort (b - a) compares numeric values This pattern compares concatenations instead For 3 vs 30: "303" vs "330" → "330" wins → 3 comes before 30 Been coding for 2 years, first time using this. Always something new to learn. #javascript #coding
Sorting Numbers for Largest Possible Number in JavaScript
More Relevant Posts
-
Codédex Daily Challenge #16 🌐 Language used: JavaScript Challenge: Given the initial state of river and a number of hours, complete the function and return what the river looks like after the dye drifts downstream. Solution: https://lnkd.in/dXQDcdMn What I did: 1. Created a new array with the same length as "river", filled entirely with water "💧". 2. Scanned the original river and recorded the index of every green patch "☘️" into the new array. 3. Spread the dye downstream. For each dye source, I marked its position plus the next "hours" position to the right as "☘️". Lesson learned: I learned how to use the array method ".fill()" to quickly generate a new array with custom content. I also practiced different loop styles, such as "forEach", to shift the dye source one position to the right after each passing hour. Thought of the day: I feel that coding is like dyeing a river: one idea can transform the whole stream. ✨😄
To view or add a comment, sign in
-
-
Day 27 of 30-day Coding Sprint 76. Minimum Window Substring - The Goal: Find the smallest substring in s that contains all characters of t (including duplicates). - The Strategy: Expand & Contract - Preprocessing: Build a frequency map (using a 256-size array) for all characters in t. - Expansion (r pointer): Move the right pointer to expand the window. If the current character is part of t and we still need more of it, increment our count. - Contraction (l pointer): Once count == m (meaning the window is "valid"), try to shrink it from the left to find the minimum possible length. - The "Squeeze": As we move l, we update our frequency map. If moving l causes us to lose a required character from t, the window becomes invalid, and we go back to expanding. Result: Efficient O(N + M) time complexity and O(256) space. #30DaysOfCode #DSASprint #LeetCode #JavaScript #SlidingWindow #HardProblem #Algorithms #Consistency
To view or add a comment, sign in
-
-
It's 5:45 am & I am still looking at my dreams. Today[2/28/2026] is day 23 of learning javascript Today & tommorow i will learn are: 1. Difference between let, const & var 2. How to use the default parameter 3. Template string, Multiline string, Dynamic string 4. Arrow Function Syntax, params 5. Spread Operator, Array Max, Copy Arrays 6. Object & Array destructuring 7. Keys, Values, Entries, Delete, Seal, Freeze 8. Accessing Object Data: Nested Object, Optional Chaining 9. Looping Object 10. Primitive Type, Non Primitive Type 11. Null Vs Undefines 12. Truthy & Falsy Values 13. ==, === , implicit conversion 14. Block Scope, Global Scope, Simple Unders. of Hoisting 15. Closure 16. Callback Function & pass different function 17. Function Arguments, pass by ref. pass by value 18. Map, ForEach 19. Filter, Find, Reduce #letsconnect #programmer #frontenddeveloper #mernstakedeveloper #Coding
To view or add a comment, sign in
-
JavaScript’s sort() can silently break your algorithms. I was solving LeetCode #350 (Intersection of Two Arrays II) using the two-pointer approach and hit an unexpected issue. I sorted the arrays like this: nums.sort() It looked fine… until it wasn’t. Example: [1, 2, 10, 5].sort() // → [1, 10, 2, 5] Why? Because JavaScript sorts lexicographically (as strings) by default. So the engine actually compares: "1", "10", "2", "5" Correct numeric sorting requires a comparator: nums.sort((a, b) => a - b) Without this, algorithms that rely on sorted arrays (binary search, two-pointer techniques, etc.) can produce incorrect results. #JavaScript #WebDevelopment #Programming #CodingTips #LeetCode #Algorithms #SoftwareEngineering #FrontendDevelopment
To view or add a comment, sign in
-
-
🚀 DSA Daily Challenge – Day 18: Longest Substring Without Repeating Characters (Medium) 🧠 A classic sliding window problem from LeetCode 3, perfect for mastering hashing + two-pointer/window techniques. 🔍 Problem Recap Given a string s, find the length of the longest substring without repeating characters. Substring must have unique characters Return max length 💡 Core Idea Instead of checking every substring (O(n²)), we can use sliding window + HashSet: 1️⃣ Use two pointers: left → start of current substring right → end of current substring 2️⃣ Maintain a HashSet of characters in current window 3️⃣ Iterate right: If s[right] exists in set → remove s[left] and move left forward Else → add s[right] to set and update maxLength This ensures every character is in the window at most once, giving linear time complexity. 🧠 Why This Works Sliding window ensures no repeated characters HashSet gives O(1) lookup Each character is added/removed at most once → O(n) time Space complexity → O(min(n, charset)) 🧩 Dry Run Example String: "abcabcbb" Window expands: "a" → "ab" → "abc" → "bca" → "cab" Max substring without repeats → "abc" → length = 3 ⚡ Pattern Connection Sliding window / two pointers Hashing for uniqueness Converting brute-force substring checking (O(n²)) → O(n) solution Builds intuition for subarray/subsequence problems #DSA #LeetCode #Day18 #Java #SlidingWindow #HashSet #Strings #CodingInterview #ProblemSolving #100DaysOfCode #DataStructures #InterviewPrep #Algorithm #MediumLevel #ProgrammingTips #CodingChallenge #LongestSubstring #NoRepeats #OptimizedCode
To view or add a comment, sign in
-
-
🧠 Day 178 — Next Greater Element 📈 Today I revised one of the most important stack pattern problems in DSA: Next Greater Element. The goal is straightforward but very useful: ✔ For every element, find the next greater element on its right ✔ If no greater element exists → return -1 This problem is a great example of combining: • Stacks • Efficient traversal techniques • Hash map lookups for fast queries Understanding this pattern unlocks solutions to many other problems like Daily Temperatures, Stock Span, and Largest Rectangle in Histogram. 🚀 DSA Journey Update Slowly building strong foundations in Stacks, Dynamic Programming, and Trees. Consistency is the real game. #DSA #Stacks #MonotonicStack #JavaScript #CodingJourney #LeetCode #ProblemSolving #ConsistencyWins
To view or add a comment, sign in
-
-
🚀 LeetCode Problem Solved: Rotate Image (Matrix Rotation) Today I practiced an interesting array/matrix problem: Rotate Image. 📌 Problem: Given an n × n matrix, rotate the image 90° clockwise in-place without using another matrix. Example: Input [ [1,2,3], [4,5,6], [7,8,9] ] Output [ [7,4,1], [8,5,2], [9,6,3] ] 💡 Key Idea: Instead of creating a new matrix, we can solve it in two steps: 1️⃣ Transpose the matrix (swap rows and columns) 2️⃣ Reverse each row This transforms the matrix into a 90° clockwise rotated image efficiently. ⚡ Time Complexity: O(n²) 📦 Space Complexity: O(1) (In-place) 🎯 Practicing problems like this helps strengthen understanding of matrix manipulation and in-place algorithms, which are very common in coding interviews. #LeetCode #DSA #JavaScript #CodingPractice #SoftwareDeveloper #Programming #TechLearning
To view or add a comment, sign in
-
-
Day 26 of 30-day Coding Sprint 992. Subarrays with K Different Integers - The Problem: Count every single contiguous subarray that contains exactly k different integers. - The Challenge: A standard sliding window is "greedy"; it finds the largest or smallest window that fits a condition. But here, multiple windows of different sizes ending at the same index r could all have exactly k integers. Approach 1: Brute Force - Generating all subarrays and checking unique counts using a HashMap. - Complexity: O(n^2). This will TLE (Time Limit Exceeded) on any competitive platform with a large input. Approach 2: The "Exactly K" via "At Most K" Logic (Optimal) - The Strategy: Just like we did with binary sums on Day 21, we use the formula: Exactly(K) = AtMost(K) - AtMost(K-1) - The Helper: helper(nums, k) counts how many subarrays have at most $k$ distinct elements. - Why it works: Finding "at most" is easy with a sliding window: if map.size > k, we shrink from the left. The number of subarrays ending at r that satisfy "at most k" is simply (r - l + 1). - Complexity: O(n) time and O(k) space. #30DaysOfCode #DSASprint #LeetCode #JavaScript #SlidingWindow #HardProblem #Algorithms #Consistency
To view or add a comment, sign in
-
-
🚀 Cracked a tricky DSA concept today — Search in Rotated Sorted Array (with duplicates) At first glance the array looks unsorted… But actually it’s two sorted arrays joined together 🔍 Example: [2,5,6,0,0,1,2] The challenge ❓ Find a target efficiently (not O(n)) → Use Modified Binary Search (O(log n)) 💡 Key Learning: 1️⃣ One half of the array is always sorted 2️⃣ Check if target lies in the sorted half 3️⃣ If duplicates confuse the search → shrink the window (left++, right--) Core logic: • All equal → ignore edges • Left sorted → search there • Else → search right side 📈 What I learned: Understanding the logic is more important than memorizing code. Today I didn’t just solve a problem — I understood how to think like an algorithm. #DSA #BinarySearch #JavaScript #CodingJourney #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
𝟒 𝐂𝐨𝐧𝐜𝐞𝐩𝐭𝐬 𝐘𝐨𝐮 𝐌𝐮𝐬𝐭 𝐊𝐧𝐨𝐰 𝐢𝐧 𝐜𝐨𝐫𝐞 𝐉𝐚𝐯𝐚🔍 ☑️ 1. What is an Anonymous Class? It’s a local class without a name, declared and instantiated in a single expression. Use Cases: Perfect for event listeners in GUI apps (like ActionListener in Swing) or when you need a quick, one-off implementation of an interface/abstract class. ☑️2. What is a Marker Interface? It’s an interface with no methods or fields. It signals metadata to the JVM or compiler. Examples: Serializable (marks class for conversion to byte stream) and Cloneable (marks class as eligible for Object.clone()). ☑️3. How to Create an Immutable Class? Think of String or Wrapper classes. Follow these rules: • Declare the class final (or use private constructors). • Make all fields private and final. • No setter methods. • If holding a mutable object (like Date/Collection), return a defensive copy in the getter. ☑️4. Can Static Methods Be Overridden? No. Static methods are hidden, not overridden. Overriding relies on runtime object type (polymorphism), but static methods are resolved at compile-time based on the reference type. . . #Javadeveloper #springbootdeveloper #javadev #spring #coding #staticmethod
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