Given an integer array nums and an integer val, remove all occurrences of val in numsin-place. Return the number of remaining elements. Order may change.
๐ง Approach
Use two pointers
fast scans array
slow records valid element positions
When nums[fast] != val, copy to nums[slow]
โ Complexity
Time: O(n)
Space: O(1)
๐ป Java Code
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { publicintremoveElement(int[] nums, int val) { intslow=0; for (intfast=0; fast < nums.length; fast++) { if (nums[fast] != val) { nums[slow] = nums[fast]; slow++; } } return slow; } }
๐ Notes
We donโt need an extra array
Just overwrite values in-place
slow pointer gives the new length
Keep grinding โ one step closer every day! ๐ช๐ฅ
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and return the new length. Do not allocate extra space for another array; you must do this by modifying the input array in-place with O(1) extra memory.
This is a direct extension of the 3Sum problem. We use sorting + two pointers:
Sort the array.
Use two nested loops for the first two numbers.
Apply the two-pointer method to find the remaining two numbers.
Skip duplicate values to avoid repeated quadruplets.
๐ง Key Insight
After fixing two indices i and j, we need to find two numbers whose sum equals target - nums[i] - nums[j]. This can be efficiently done with a two-pointer scan since the array is sorted.
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
๐ฌ Examples
Example 1
1 2 3
Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2 (-1 + 2 + 1 = 2).
๐ก Intuition
The problem is similar to the classic 3Sum, but instead of finding an exact match, we want the closest sum. We can sort the array first, then use a two-pointer approach to efficiently explore possible triplets.
Explanation: There is no common prefix among the input strings.
๐ก Intuition
A common and simple approach is to start from the first string as the prefix, and then gradually shorten it while checking against other strings. Stop when the prefix no longer matches.
๐ข Java Code (Vertical Scanning)
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) return""; Stringprefix= strs[0]; for (inti=1; i < strs.length; i++) { while (strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length() - 1); if (prefix.isEmpty()) return""; } } return prefix; } }
โฑ Complexity Analysis
Time: O(S) โ S = total number of characters in all strings (each char checked at most once).
Space: O(1) โ no extra data structure used.
โ๏ธ Summary
Start with the first string as prefix and reduce it when mismatches occur.
Efficient for small/medium input sizes.
A clean and intuitive string problem that often appears early in interviews.
Convert a Roman numeral to an integer. Input is guaranteed to be within the range corresponding to standard Roman numerals (typically 1..3999).
Roman numerals are represented by the symbols: I(1), V(5), X(10), L(50), C(100), D(500), M(1000). Some symbols may be placed before larger symbols to indicate subtraction, e.g., IV = 4, IX = 9.
๐ฌ Examples
Example 1
1 2
Input: s = "III" Output: 3
Example 2
1 2
Input: s = "IV" Output: 4
Example 3
1 2
Input: s = "MCMXCIV" Output: 1994
๐ก Intuition (Greedy / Left-to-right)
Scan from left to right, adding values. If a smaller-value symbol appears before a larger one, subtract the smaller; otherwise add it. A simple approach: for each character, compare its value with the next character (if any) to decide add or subtract.
intn= s.length(); intresult=0; for (inti=0; i < n; i++) { intval= map.get(s.charAt(i)); if (i + 1 < n && val < map.get(s.charAt(i + 1))) { result -= val; } else { result += val; } } return result; } }
โฑ Complexity Analysis
Time: O(n) โ single pass over the string.
Space: O(1) โ constant-size map and a few variables.
โ๏ธ Summary
Use a mapping from Roman symbols to integers.
Subtract when a smaller symbol precedes a larger one; otherwise add.
Simple, linear-time solution ideal for interviews.
Convert an integer to a Roman numeral. Input is guaranteed to be within the range 1 <= num <= 3999.
๐ฌ Examples
Example 1
1 2
Input: num = 3 Output: "III"
Example 2
1 2 3
Input: num = 58 Output: "LVIII" Explanation: L = 50, V = 5, III = 3.
Example 3
1 2 3
Input: num = 1994 Output: "MCMXCIV" Explanation: M = 1000, CM = 900, XC = 90, IV = 4.
๐ก Intuition (Greedy)
Use a greedy approach: repeatedly subtract the largest Roman value that does not exceed the current number and append its symbol. Predefine pairs of values and symbols in decreasing order (including subtractive forms like 900 -> โCMโ).
๐ข Java Code (Greedy)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public String intToRoman(int num) { int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; String[] symbols = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; StringBuildersb=newStringBuilder(); for (inti=0; i < values.length && num > 0; i++) { while (num >= values[i]) { num -= values[i]; sb.append(symbols[i]); } } return sb.toString(); } }
โฑ Complexity Analysis
Time: O(1) โ bounded by a small constant (max ~15 symbol appends).
Space: O(1) โ output size is O(1) relative to input bounds.
โ๏ธ Summary
Predefine Roman symbols including subtractive pairs.
Greedy subtraction + append produces correct Roman numeral efficiently.
Java implementation above is simple and interview-friendly.
LeetCode 8 - String to Integer (atoi) Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++โs atoi function).
The algorithm follows these steps:
Read and ignore leading whitespaces.
Check if the next character is + or - (determine the sign).
Read digits until a non-digit character or end of string.
Clamp the result within the 32-bit integer range.
Example:
1 2 3 4 5 6 7 8
Input: s = "42" Output: 42
Input: s = " -42" Output: -42
Input: s = "4193 with words" Output: 4193
๐ก First Thought (Use Built-in Functions)
One might think of using Integer.parseInt() or similar methods, but those cannot handle invalid formats and overflow gracefully. We need to implement the parsing logic manually.
โ๏ธ Optimized Approach โ Manual Parsing
We manually iterate through the string, handle spaces, sign, digits, and overflow.