Thanks to visit codestin.com
Credit goes to t.me

NullPointerDev
8 subscribers
144 photos
1 file
4 links
๐Ÿ‘จ๐Ÿผโ€๐Ÿ’ปJava developer with extraordinary stack and interesting tasks

๐Ÿ’ปWalk this way with me

๐Ÿ›œCheck out my GitHub and share your experience: https://github.com/NullPoint3rDev
Download Telegram
๐Ÿงฎ Java Solution: Generate String from T/F Constraints (LeetCode 3474)

Problem: Build smallest string where substrings must equal (T) or not equal (F) to str2.

๐Ÿง  Explanation:
Initialize all with 'a' (smallest letter)
T constraints: fix exact characters from str2, detect conflicts
F constraints: if substring already equals str2, modify rightmost unfixed position to 'b'
This ensures lexicographically smallest result

๐Ÿ“Š Example: s="TFTF", t="ab"
T at 0: ans[0]='a', ans[1]='b'
T at 2: ans[2]='a', ans[3]='b'
F at 1: substring "ba" โ‰  "ab" โœ“
F at 3: substring "b?" โ†’ change ans[4] from 'a' to 'b'? Wait, must be โ‰  "ab" โ†’ 'a' works? Actually "ba" โ‰  "ab" already. Code uses rightmost unfixed position. Returns "ababa" โœ…

โฑ๏ธ Complexity: O(nร—m) time, O(n+m) space

๐ŸŽฏ Key Learning Points:
- Two-Phase Algorithm - Process T constraints first (mandatory), then F constraints.
- Conflict Detection - Check fixed positions against required characters.

#LeetCode #Hard
๐Ÿ‘จโ€๐Ÿ’ป2๐Ÿค“1
๐Ÿงฎ Java Solution: Robot Collision Simulation (LeetCode 2751)

Problem: Robots on a line move R or L. When two meet, higher health survives (health-1), equal health both die. Return surviving healths in original order.

๐Ÿง  Explanation:
Sort by position. Stack holds right-moving robots. When left-moving robot appears, collide with stack top: higher health survives (health-1), lower dies, equal both die.

๐Ÿ“Š Example: positions=[3,5,2,6], healths=[10,10,15,12], dir="RLRL"
Sort by position: [2(R),3(R),5(L),6(L)]
2(R) push, 3(R) push
5(L) collides with 3(R): 10 vs 10 โ†’ both die, pop
6(L) collides with 2(R): 15 vs 10 โ†’ 2 dies, 6 health=14
Survivor: [14] โœ…

โฑ๏ธ Complexity: O(n log n) time (sorting), O(n) space

๐ŸŽฏ Key Learning Points:
- Sort by Position - Process collisions in spatial order for correct simulation.
- Stack for Right-Moving Robots - Track potential collision targets for left-moving robots.

#LeetCode #Hard
๐Ÿ‘จโ€๐Ÿ’ป2๐Ÿค“1
๐Ÿงฎ Java Solution: Maximum Coins with Neutralizations (LeetCode 3418)

Problem: Robot moves right/down from (0,0) to (m-1,n-1). Negative cells are robbers (steal |value|). Can neutralize at most 2 robbers. Maximize total coins.

๐Ÿง  Explanation:
DFS with memoization: state = (i, j, k) where k = neutralizations left (0-2)
At each cell: either take value (negative reduces sum) or neutralize (skip negative if k>0)
Base case: last cell can be neutralized if k>0 (take 0 instead of negative)

๐Ÿ“Š Example: coins=[[0,1,-1],[1,-2,3],[2,-3,4]]
Path: (0,0)=0, (0,1)=1, (1,1) neutralize -2 (k=1), (1,2)=3, (2,2)=4 โ†’ total 8 โœ…

โฑ๏ธ Complexity: O(mร—nร—3) time & space

๐ŸŽฏ Key Learning Points:
- Top-Down DP - Use recursion with memoization for clean state management.
- State Definition - (i,j,k) where k tracks remaining neutralizations.
- Decision Branching - Try both taking and neutralizing negative cells.

#LeetCode #Medium
๐Ÿ‘1๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Maximum Walls Destroyed by Robots (LeetCode 3661)

Problem: Each robot fires one bullet left or right up to max distance. Bullets stop at robots. Maximize unique walls destroyed.

๐Ÿง  Explanation:
Sort robots by position, sort walls. DP state: (robot index, canShootRight flag)
For each robot: try shooting left (covers [pos-dist, pos]) or right (covers [pos+1, pos+dist])
Left shots blocked by previous robot's position+1; right shots blocked by next robot's shot range
Use binary search to count walls in range

๐Ÿ“Š Example: robots=[10,2], dist=[5,1], walls=[5,2,7]
Sorted robots: [2(R1),10(R2)]
R1 shoots left: covers [1,2] โ†’ destroys wall 2
R2 shoots left: covers [5,10] โ†’ destroys walls 5,7
Total=3 โœ…

โฑ๏ธ Complexity: O(n log n) time, O(n) space

๐ŸŽฏ Key Learning Points:
- Sorting - Process robots left-to-right after sorting by position.
- State DP - Track robot index and whether right shot allowed (blocked by next robot).

#LeetCode #Hard
๐Ÿ‘1๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Decode Slanted Transposition Cipher (LeetCode 2075)

Problem: Given encoded string and number of rows, recover original string placed in matrix along diagonals (top-left to bottom-right), then read row-wise.

๐Ÿง  Explanation:
Matrix has rows and cols = encodedText.length() / rows
Original text was placed along diagonals (i=0,j=0 โ†’ i=1,j=1 โ†’ ...)
To decode: read all diagonals starting from first row, each column j as starting point
Collect characters in diagonal order, then trim trailing spaces

๐Ÿ“Š Example: encodedText="ch ie pr", rows=3, cols=4
Traverse: (0,0)=c, (0,1)=h, (0,2)=' ', (0,3)=' ', (1,0)=i, (1,1)=e, (2,0)=p, (2,1)=r โ†’ collect: "ch i e p r" โ†’ trim trailing spaces โ†’ "cipher" โœ…

โฑ๏ธ Complexity: O(rows ร— cols) = O(encodedText.length()) time, O(n) space

๐ŸŽฏ Key Learning Points:
- Matrix Dimensions - Compute cols from length/rows.
- Diagonal Traversal - Start each diagonal at (0, j) and move down-right (x++, y++).

#LeetCode #Medium
๐Ÿ”ฅ1๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Robot Return to Origin (LeetCode 657)

Problem: Determine if robot returns to (0,0) after sequence of U/D/R/L moves.

๐Ÿง  Explanation:
Track x (horizontal) and y (vertical) coordinates
R increases x, L decreases x; U increases y, D decreases y
After processing all moves, robot is at origin if both coordinates are zero

๐Ÿ“Š Example: "UD" โ†’ y:0โ†’1โ†’0, x:0โ†’0โ†’0 โ†’ true โœ…
"LL" โ†’ x:0โ†’-1โ†’-2, y:0โ†’0โ†’0 โ†’ false โœ…

โฑ๏ธ Complexity: O(n) time, O(1) space

๐ŸŽฏ Key Learning Points:
- Coordinate System - Track position using (x,y) pairs.
- Switch Statement - Efficient character handling for four directions.
- Pair Annihilation - U cancels D, R cancels L regardless of order.

#LeetCode #Easy
๐Ÿ‘1๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Robot Simulation with Obstacles (LeetCode 874)

Problem: Simulate robot moving north/east/south/west, avoiding obstacles. Return max squared distance from origin.

๐Ÿง  Explanation:
Track (x,y) and direction (0-3). Store obstacles in HashSet for O(1) checks.
Commands: -1 turn right, -2 turn left, 1-9 move step-by-step.
After each step, update max squared distance. Stop movement when obstacle encountered.

๐Ÿ“Š Example: commands=[4,-1,3], obstacles=[]
North 4โ†’(0,4), turn right, east 3โ†’(3,4), maxDist=25 โœ…

โฑ๏ธ Complexity: O(commands ร— 9) time, O(obstacles) space

๐ŸŽฏ Key Learning Points:
- Direction Encoding - Map 0=N,1=E,2=S,3=W for modulo rotation.
- HashSet Lookup - Store obstacles as strings for O(1) collision detection.
- Step-by-Step Movement - Process one unit at a time to detect mid-path obstacles.

#LeetCode #Medium
๐Ÿ”ฅ1๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Robot Walking Grid Perimeter (LeetCode 2069)

Problem
: Robot moves along grid boundary, turning counterclockwise when hitting edge. Return position and direction after many steps.

๐Ÿง  Explanation:
Robot only moves on perimeter. One full cycle = 2ร—(w+h-2) steps.
Instead of simulating each step, accumulate total steps.
Position and direction derived from (totalSteps % perimeter) using 4 edge segments.
Special case: after full cycle, robot at (0,0) facing South.

๐Ÿ“Š Example: width=6,height=3, perimeter=14
steps=4 โ†’ (4,0) East โœ…
steps=6 โ†’ (5,1) North โœ…

โฑ๏ธ Complexity: O(1) per call, O(1) space

๐ŸŽฏ Key Learning Points:
- Cycle Detection - Robot repeats path every perimeter steps.
- Modulo Optimization - Reduce millions of steps to single cycle.
- Edge Segmentation - Break perimeter into 4 linear segments.

#LeetCode #Medium
๐Ÿ‘1๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Array Multiplication with Step Queries (LeetCode 3653)

Problem: Apply queries [li, ri, ki, vi] to multiply nums[idx] by vi for idx = li, li+ki, li+2ki... โ‰ค ri. Return XOR of final array.

๐Ÿง  Explanation:
Loop through each query. For current query, iterate indices from li to ri with step ki.
Multiply each nums[idx] by vi modulo 1e9+7 using long to avoid overflow.
After all queries, XOR all elements for final answer.

๐Ÿ“Š Example: nums=[2,3,1,5,4], queries=[[1,4,2,3],[0,2,1,2]]
Query1: idx=1โ†’9, idx=3โ†’15 โ†’ [2,9,1,15,4]
Query2: idx=0โ†’4, idx=1โ†’18, idx=2โ†’2 โ†’ [4,18,2,15,4]
XOR: 4^18=22, 22^2=20, 20^15=27, 27^4=31 โœ…

โฑ๏ธ Complexity: O(q ร— n) time worst case, O(1) space

๐ŸŽฏ Key Learning Points:
- Step Iteration - Traverse array with custom step ki instead of incrementing by 1.
- Modular Multiplication - Use modulo 1e9+7 with long casting to prevent overflow.
- Nested Loops - Process queries sequentially, updating array in place.

#LeetCode #Medium
๐Ÿ‘1๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ C++ Solution: Range Multiplication Queries with Step k (LeetCode 3655)

Problem
: Apply queries [li, ri, ki, vi] to multiply nums[idx] by vi for idx = li, li+ki, li+2ki... โ‰ค ri. Return XOR of final array.

๐Ÿง  Explanation: Split queries by k with threshold โˆšn. Small k: difference array with modular inverses (store multiplier at l, inverse beyond r, propagate). Large k: process directly. Finally apply multipliers and XOR.

๐Ÿ“Š Example: nums=[2,3,1,5,4], queries=[[1,4,2,3],[0,2,1,2]]
k=2 (small): diff[1]=3, diff[3]=inv(3) at r+? Actually r adjusted to last index in progression. Propagate to indices 1,3.
k=1 (small): diff[0]=2, diff[3]=inv(2), propagate to all indices.
Result: [4,18,2,15,4] XOR=31 โœ…

โฑ๏ธ Complexity: O((n+q)ยทโˆšn) time, O(nยทโˆšn) space

๐ŸŽฏ Key Learning Points:
- Square Root Decomposition - Balance between small and large step queries.
- Modular Inverse - Use Fermat's theorem when MOD is prime (1e9+7).

#LeetCode #Hard
๐Ÿค“2๐Ÿ‘1
๐Ÿงฎ Java Solution: Minimum Distance of Good Tuple (LeetCode 3740)

Problem: Find three equal numbers in array minimizing abs(i-j)+abs(j-k)+abs(k-i).

๐Ÿง  Explanation:
For i<j<k, distance = (j-i)+(k-j)+(k-i) = 2ร—(k-i). So only first and last index matter.
Group indices by value. For each value with โ‰ฅ3 indices, check consecutive triples in sorted order. The smallest k-i gives minimal distance.

๐Ÿ“Š Example: nums=[1,2,1,1,3]
Value 1 indices: [0,2,3]. Triple (0,2,3): 2ร—(3-0)=6 โœ…

โฑ๏ธ Complexity: O(n) time, O(n) space

๐ŸŽฏ Key Learning Points:
- Distance Simplification - For three sorted points, sum of pairwise distances = 2ร—(last-first).
- Index Grouping - Use HashMap to collect positions of each value.
- Consecutive Triple Check - Only need to check consecutive indices (minimum spread).

#LeetCode #Easy
๐Ÿ‘1๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Minimum Distance of Good Tuple (LeetCode 3741)

Problem: Find three equal numbers in array minimizing abs(i-j)+abs(j-k)+abs(k-i).

๐Ÿง  Explanation:
For sorted indices i<j<k, distance = (j-i)+(k-j)+(k-i) = 2ร—(k-i). Only first and last index matter. Group indices by value. For each value with โ‰ฅ3 indices, check consecutive triples (t, t+1, t+2). Their distance = 2ร—(indices[t+2] - indices[t]). This gives minimal spread with at least one index in between.

๐Ÿ“Š Example: nums=[1,2,1,1,3]
Value 1 indices: [0,2,3]. Triple (0,2,3): 2ร—(3-0)=6 โœ…

โฑ๏ธ Complexity: O(n) time, O(n) space

๐ŸŽฏ Key Learning Points:
- Distance Formula - For three sorted points, sum of pairwise distances = 2ร—(last-first).
- Index Grouping - Use HashMap to collect positions for each distinct value.
- Consecutive Triple Check - Only need indices[t], indices[t+1], indices[t+2] for minimal spread.

#LeetCode #Medium
๐Ÿค“2๐Ÿ‘1
๐Ÿงฎ Java Solution: Minimum Distance to Type Word with Two Fingers (LeetCode 1320)

Problem: Type a string using two fingers on a keyboard grid. Minimize total Manhattan distance between consecutive finger positions. Initial positions are free.

๐Ÿง  Explanation:
DP state: after typing i characters, positions of both fingers. First char typed by either finger (cost 0). For each new char, either move the finger that typed previous char, or move the other finger (if it was free). Use Manhattan distance on 6x5 keyboard grid.

๐Ÿ“Š Example: "CAKE" โ†’ C(2,0), A(0,0), K(2,3), E(0,3). Optimal: Cโ†’A (2), Kโ†’E (1) total=3 โœ…

โฑ๏ธ Complexity: O(n ร— 26ยฒ) time, O(n ร— 26ยฒ) space

๐ŸŽฏ Key Learning Points:
- 3D Dynamic Programming - State includes position of both fingers.
- Keyboard Coordinate Mapping - Convert letter to (x,y) using row = (char)/6, col = (char)%6.
- Two-Finger Typing - One finger types previous char, either finger can type next.

#LeetCode #Hard
๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Find Closest Index to Target (LeetCode 1848)

Problem: Find index i where nums[i] == target that minimizes |i - start|. Return that minimum distance.

๐Ÿง  Explanation:
Scan array from left to right. Whenever target found, compute distance from start using absolute difference. Track minimum distance seen. Return final minimum.

๐Ÿ“Š Example: nums=[1,2,3,4,5], target=5, start=3
Only index 4 has target: |4-3|=1 โœ…

โฑ๏ธ Complexity: O(n) time, O(1) space

๐ŸŽฏ Key Learning Points:
- Linear Search - Iterate through array to find matching elements.
- Absolute Difference - Use Math.abs() to measure distance regardless of direction.
- Minimum Tracking - Initialize with MAX_VALUE, update using Math.min().

#LeetCode #Easy
๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Minimum Total Distance Traveled (LeetCode 2463)

Problem: Assign robots to factories with limits to minimize sum of distances.

๐Ÿง  Explanation:
Sort robots and factories by position. DP state: (robot index i, factory index j) = min distance to assign robots from i onward using factories from j onward. For current factory, either skip it or assign its limit of consecutive robots (optimal assignment keeps order).

๐Ÿ“Š Example: robots=[0,4,6], factories=[[2,2],[6,2]]
Assign robots 0,4 to factory 2 (dist=2+2=4), robot 6 to factory 6 (dist=0) total=4 โœ…

โฑ๏ธ Complexity: O(r ร— f ร— limit) time, O(r ร— f) space

๐ŸŽฏ Key Learning Points:
- Sorting - Sort robots and factories by position for optimal assignment.
- DP State Definition - (robot index, factory index) = minimum cost to assign remaining robots.
- Skip Factory Option - Leave current factory unused.

#LeetCode #Hard
๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Shortest Distance in Circular Array (LeetCode 2515)

Problem: Find minimum steps from startIndex to any occurrence of target in circular array.

๐Ÿง  Explanation:
Scan array to find all indices where word equals target. For each index, compute direct distance |i-start| and circular distance n - direct (going the other way around). Take minimum of both. Track global minimum across all matching indices. Return -1 if target not found.

๐Ÿ“Š Example: words=["hello","i","am","leetcode","hello"], target="hello", start=1
Indices 0 and 4: dist(0)=min(1,4)=1, dist(4)=min(3,2)=2 โ†’ min=1 โœ…

โฑ๏ธ Complexity: O(n) time, O(1) space

๐ŸŽฏ Key Learning Points:
- Circular Distance - For indices i and j in array length n, min distance = min(|i-j|, n-|i-j|).
- String Comparison - Use .equals() for content comparison, not ==.

#LeetCode #Easy
๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Circular Array Nearest Same Value (LeetCode 3488)

Problem: For each query index, find minimum circular distance to another index with same value.

๐Ÿง  Explanation:
Group indices by value using HashMap. For each group with โ‰ฅ2 indices, consider circular neighbors in the sorted list. For each index, compute circular distance to prev and next using min(|a-b|, n-|a-b|). Store minimum. Query answers are precomputed.

๐Ÿ“Š Example: nums=[1,3,1,4,1,3,2], queries=[0,3,5]
Value 1 indices [0,2,4]: index0โ†’min(dist to 2, dist to 4)=min(2,3)=2
Value 3 indices [1,5]: index5โ†’dist to 1 = min(4,3)=3 โ†’ answer[0,3,5]=[2,-1,3] โœ…

โฑ๏ธ Complexity: O(n) time, O(n) space

๐ŸŽฏ Key Learning Points:
- Index Grouping - Group indices by value for efficient processing.
- Circular Distance - Distance = min(|a-b|, n-|a-b|).
- Neighbor Check - Only need nearest neighbors in sorted circular list.

#LeetCode #Medium
๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1
๐Ÿงฎ Java Solution: Minimum Mirror Pair Distance (LeetCode 3761)

Problem: Find minimum distance between indices i<j where reverse(nums[i]) == nums[j].

๐Ÿง  Explanation:
Single pass with HashMap. For each index i, check if nums[i] was previously seen as a reversed value. If yes, update min distance. Then store current index mapped to reverse(nums[i]) for future matches. This finds pairs (j,i) where j < i and reverse(nums[j]) == nums[i].

๐Ÿ“Š Example: nums=[12,21,45,33,54]
i=0: reverse(12)=21 โ†’ pos={21โ†’0}
i=1: nums[1]=21 found in pos (key 21) โ†’ distance=1-0=1 โœ… ans=1, pos={21โ†’0,12โ†’1}
i=2: reverse(45)=54 โ†’ pos={...,54โ†’2}
i=3: reverse(33)=33 โ†’ pos={...,33โ†’3}
i=4: nums[4]=54 found in pos (key 54) โ†’ distance=4-2=2 โ†’ ans=1 โœ…

โฑ๏ธ Complexity: O(n) time, O(n) space

๐ŸŽฏ Key Learning Points:
- Single Pass HashMap - Process array once, store needed values for future lookups.
- Reverse Digit Function - Handle leading zeros automatically with integer arithmetic.

#LeetCode #Medium
๐Ÿค“1
๐Ÿงฎ Java Solution: Mirror Distance of a Number (LeetCode 3783)

Problem: Calculate absolute difference between n and its digit-reversed version.

๐Ÿง  Explanation:
Extract digits from right to left using modulo and division. Build reversed number by multiplying current result by 10 and adding each digit. Leading zeros automatically disappear since integer conversion drops them. Return absolute difference.

๐Ÿ“Š Example: n=25 โ†’ reverse=52 โ†’ |25-52|=27 โœ…
n=10 โ†’ reverse=1 โ†’ |10-1|=9 โœ…
n=7 โ†’ reverse=7 โ†’ |7-7|=0 โœ…

โฑ๏ธ Complexity: O(log n) time, O(1) space

๐ŸŽฏ Key Learning Points:
- Digit Extraction - Use n%10 to get last digit, n/=10 to remove it.
- Number Reversal - Build new number by rev*10 + digit each iteration.
- Leading Zero Handling - Integers automatically ignore leading zeros (e.g., 10โ†’1).

#LeetCode #Easy
๐Ÿค“2
๐Ÿงฎ Java Solution: Maximum Distance in Non-Increasing Arrays (LeetCode 1855)

Problem: Maximize j-i where iโ‰คj and nums1[i] โ‰ค nums2[j] with both arrays non-increasing.

๐Ÿง  Explanation:
Binary search for each i to find rightmost j in nums2 where nums2[j] โ‰ฅ nums1[i]. Because nums2 is non-increasing, valid j form a suffix. Track maximum j-i. Time complexity O(n log m).

๐Ÿ“Š Example: nums1=[55,30,5,4,2], nums2=[100,20,10,10,5]
i=2: nums1[2]=5, binary search finds j=4 (nums2[4]=5) โ†’ dist=2 โœ…

โฑ๏ธ Complexity: O(n log m) time, O(1) space

๐ŸŽฏ Key Learning Points:
- Binary Search - Find rightmost index satisfying condition in monotonic array.
- Non-Increasing Property - Enables binary search for valid j suffix.
- Condition iโ‰คj - Ensure left starts at i for valid indices.

#LeetCode #Medium
๐Ÿค“1๐Ÿ‘จโ€๐Ÿ’ป1