Day 92/100 Problem Statement : Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal. Input: s1 = "sea", s2 = "eat" Output: 231 Solution : https://lnkd.in/gm8-CDmm public int minimumDeleteSum(String s1, String s2) { int m = s1.length(), n = s2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = m - 1; i >= 0; i--) { for (int j = n - 1; j >= 0; j--) { if (s1.charAt(i) == s2.charAt(j)) { dp[i][j] = s1.charAt(i) + dp[i + 1][j + 1]; } else { dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]); } } } int total = 0; for (char c : s1.toCharArray()) total += c; for (char c : s2.toCharArray()) total += c; return total - 2 * dp[0][0]; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
Minimum ASCII Sum of Deleted Characters to Equal Strings
More Relevant Posts
-
Day 97/100 Problem Statement : You are given the two integers, n and m and two integer arrays, hBars and vBars. The grid has n + 2 horizontal and m + 2 vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from 1. You can remove some of the bars in hBars from horizontal bars and some of the bars in vBars from vertical bars. Note that other bars are fixed and cannot be removed. Return an integer denoting the maximum area of a square-shaped hole in the grid, after removing some bars (possibly none). Input: n = 2, m = 1, hBars = [2,3], vBars = [2] Output: 4 Solution : https://lnkd.in/gJ4FkbK9 public int maximizeSquareHoleArea(int n, int m, int[] hBars, int[] vBars) { Arrays.sort(hBars); Arrays.sort(vBars); int s = Math.min(maxSpan(hBars), maxSpan(vBars)); return s * s; } private int maxSpan(int[] bars) { int res = 1, streak = 1; for (int i = 1; i < bars.length; i++) { if (bars[i] - bars[i - 1] == 1) streak++; else streak = 1; res = Math.max(res, streak); } return ++res; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
To view or add a comment, sign in
-
🔥Day 91 of #100DaysOfLeetCode Problem: 1653. Minimum Deletions to Make String Balanced Difficulty: Medium Key Insight: A balanced string must have all 'a's before all 'b's. Any 'b' before an 'a' creates a violation. Approach: Preprocess the string using: - prefixB[i]: number of 'b's strictly before index i - suffixA[i]: number of 'a's strictly after index i For every index i, treat it as a split point and compute: deletions = prefixB[i] + suffixA[i] The minimum over all splits is the answer. Time Complexity: O(n) Space Complexity: O(n) #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
To view or add a comment, sign in
-
-
📁 File Handling 🌊Character streams deal with Unicode characters 🌍 👉 They are meant for text, not raw binary data like byte stream.| ✔️ FileWriter → can create a file if it doesn’t exist ✨ ❌ FileReader → never creates a file 👉 If file doesn’t exist → FileNotFoundException 🚫 Reading rules 📖 ✔️ read() returns -1 at end of file 🛑 ✔️ Correct pattern: while ((ch = reader.read()) != -1) 🔁 File deletion 🗑️ ✔️ file.delete() ✔️ Returns boolean (true / false) ❓ Why no exception? 👉 Because streams are irrelevant for delete ❌ Character streams CANNOT update content in the middle of a file ✔️ Same rule as byte streams Why? 🤔 👉 Files are linear 📏 👉 There is no “insert here” operation 👉 You can only read forward or write forward What “update” actually means in Java 🧠 There is ONLY one way 👇 1️⃣ Read entire file (FileReader) 📖 2️⃣ Modify content in memory (String / StringBuilder) 🧩 3️⃣ Rewrite entire file (FileWriter) ✍️ ✅ This is the only real update mechanism Append ≠ Update ⚠️ 👉 Files store bytes; FileReader interprets bytes as characters, FileInputStream does not. GitHub Link: https://lnkd.in/g9843mcC 🔖Frontlines EduTech (FLM) #Java #JavaIO #FileHandling #ByteStream #CharacterStream #FileInputStream #FileReader #Unicode #JVM #JavaConcepts #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #BackendDevelopment #Programming #Java #FileHandling #CharacterStreams #Unicode #FileReader #FileWriter #BackendConcepts #LearningInPublic
To view or add a comment, sign in
-
-
Transformed Array: Leetcode Problem link:https://lnkd.in/gHFR9qwp Idea: For every index i, the value nums[i] tells me where to move next. If nums[i] == 0 → no movement, so result[i] = nums[i] If nums[i] > 0 → move right nums[i] steps (wrapping from last index back to 0) If nums[i] < 0 → move left abs(nums[i]) steps (wrapping from 0 back to last index) How I implemented it: I loop through each index i. I call a helper method moveIndex(n, i, shift) which moves one step at a time: right if shift is positive left if shift is negative wraps around at the edges Once I get the newIndex, I set: result[i] = nums[newIndex] #Java #DSA #Algorithms #ProblemSolving #CleanCode #CodingInterview #BackendEngineering
To view or add a comment, sign in
-
-
#Day 63: LeetCode 1984 - Minimum Difference Between Highest and Lowest of K Scores Code:- import java.util.Arrays; class Solution { public int minimumDifference(int[] nums, int k) { // Step 1: Handle the edge case where only one score is picked if (k == 1) return 0; // Step 2: Sort the scores to bring close values together Arrays.sort(nums); int minDiff = Integer.MAX_VALUE; // Step 3: Slide a window of size k through the array // The window starts at 'i' and ends at 'i + k - 1' for (int i = 0; i <= nums.length - k; i++) { int currentDiff = nums[i + k - 1] - nums[i]; // Step 4: Update the global minimum difference if (currentDiff < minDiff) { minDiff = currentDiff; } } return minDiff; } } #The Strategy: ->Sort the scores to align them by magnitude. ->Apply a Sliding Window of size $k$ to look at every possible 'cluster' of scores. ->Calculate the spread (Max - Min) for each cluster and capture the minimum. #100DaysOfCode #Java #SoftwareEngineering #Algorithms #LeetCode #SDE #ProblemSolving #SlidingWindow"
To view or add a comment, sign in
-
-
🚀 The char Data Type (Java) The `char` data type represents a single 16-bit Unicode character. It is used to store characters such as letters, digits, and symbols. Character literals are enclosed in single quotes (e.g., `'A'`, `'5'`, `'$'`). The `char` type can also represent Unicode escape sequences for special characters. Understanding `char` is fundamental for working with text and strings in Java. #Java #JavaDev #OOP #Backend #professional #career #development
To view or add a comment, sign in
-
-
📌 Day 18,19,20 – Understanding Arrays in Java On Day 18,19,20, I learned one of the most fundamental static data structures in Java — Arrays. 🔹 What is an Array? An array is an object used to store and retrieve multiple elements of the same data type efficiently. It helps organize data and enables faster access using index positions. 🔹 Key Observations About Arrays: Dimensionality → 1D, 2D, 3D arrays Homogeneous Data → Arrays store only the same data type Structure → Regular arrays & Jagged arrays 🔹 Array Syntax: int[] a = new int[5]; Arrays are created using the new keyword, which allocates memory in the Heap segment. 🔹 Important Concepts: Array index always starts from 0 Traversing elements from start to end is called array traversal Arrays are objects, not primitive data types 🔹 Types of Arrays: 1D Array → Single row structure 2D Array → Rows and columns 3D Array → Blocks, rows, and columns 🔹 Regular vs Jagged Array: Regular Array → Equal number of columns in every row Jagged Array → Unequal number of columns in rows 🔹 Returning an Array from a Method: When an array is returned from a method, the JVM creates an object, and the reference of that object is returned to the calling method. Understanding arrays builds a strong foundation for DSA, memory management, and real-world problem solving 🚀 #Java #CoreJava #Arrays #DataStructures #JVM #HeapMemory #LearningJourney #Day18
To view or add a comment, sign in
-
-
Day - 65 Letter Combinations of Phone Number The problem - Given string of digits 2-9, return all possible letter combinations that the number could represent (like old phone keypads). Example : digits = "23" → ["ad","ae","af","bd","be","bf","cd","ce","cf"] Brute Force - Generate all combinations iteratively using nested loops - works but becomes unwieldy with variable input length. Approach Used - •)Create map, 2→"abc", 3→"def", 4→"ghi", 5→"jkl", 6→"mno", 7→"pqrs", 8→"tuv", 9→"wxyz" •) Handle edge case, if digits is null or empty, return empty list. •) Initialize, call backtrack(digits, 0, new StringBuilder(), res, map). •) Backtrack(digits, idx, comb, res, map), 1 - Base Condition, if idx == digits.length, add comb to res. 2 - Recursive case, get letters for current digit, String letters = map.get(digits.charAt(idx)). 3 - For each letter, append to comb, recurse with idx+1, backtrack(digits, idx + 1, comb, res, map). Remove last character, comb.deleteCharAt(comb.length() - 1). Complexity - Time - O(4^n × n), max 4 letters per digit, n to build each string. Space - O(n), recursion depth. Note - Use map for digit→letters. For each digit, try all its letters, recurse to next digit. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🌙Shallow Copy (clone / Arrays.copyOf) of an array ☐☐☐ Outer array becomes new ✅ Inner arrays are still SAME references ❌ So if you change inside value → both change. ✅ original and shallow point to different outer arrays (different addresses) ❌ but original[i] and shallow[i] point to the same inner row arrays (same addresses) In one line:✅ “Two variables point to different outer arrays, but the rows inside are pointing to the same memory.” ✅ in shallow copy, outer array is new, but the rows are shared, so changing a cell changes both. ❌If you assign a new 1D row to the copied 2D array, only that row becomes different in the copy; the other rows still stay shared with original. A 2D array in Java is actually: ✅ “array of references to 1D arrays” So when you clone the outer array, Java copies: the list of references (outer) not the actual row arrays (inner) Cell change: shallow[0][0] = 5 ➡️ You edited the same shared row → both see it ✅ Row replacement: shallow[0] = new int[]{...} ➡️ You changed only which row reference shallow points to → original remains same ✅ ✅ toString() prints only the memory address of inner arrays (useless). ✅ Arrays.deepToString() prints the actual values inside all rows (proper output). GitHub Link: https://lnkd.in/g2j8X_-z 🔖Frontlines EduTech (FLM) #Java #Arrays #DeepCopy #2DArray #JavaProgramming #Coding #DSA #ProgrammingBasics #LearnJava #CodeSnippet
To view or add a comment, sign in
-
-
Day - 61 Subsets II The problem - Given array that may contain duplicates, return all possible unique subsets. Example : candidates = [10,1,2,7,6,1,5], target = 8 → [[1,1,6],[1,2,5],[1,7],[2,6]] Brute Force - Generate all combinations iteratively, still exponential, but less elegant than recursion. Approach Used - •) Sort the nums array.nums.lengthcktrack(0, nums, subset, res). •) Base case, if i == nums.length, reached end, add new ArrayList(subset) to res and return. •) Recursive First case, include nums[i], add to subset, recurse with i+1, backtrack (remove). •) Recursive Second case, exclude nums[i], recurse with i+1 (don't add). Complexity - Time - O(2^n), each element include/exclude. Space - O(n), recursion depth. Note - Sort array. After excluding an element, skip all duplicates before next recursion to avoid duplicate subsets. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
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