Java Topic
Live Coding Interview Questions (1 to 20)
Question 1: Check if ransom note can be constructed from magazine letters.
You are given two strings:
-
ransomNote — the text you want to create
-
magazine — the collection of letters available
Write a function that returns true if the ransom note can be constructed from the letters in the magazine.
Each letter in the magazine may only be used once.
Sample Inputs and Outputs
Example 1
Input:
ransomNote = "a"
magazine = "b"
Output:
false
Example 2
Input:
ransomNote = "aa"
magazine = "ab"
Output:
false
Example 3
Input:
ransomNote = "aa"
magazine = "aab"
Output:
true
// C#
public static bool CanConstruct(string ransomNote, string magazine) {
Dictionary<char, int> counts = new Dictionary<char, int>();
foreach (char c in magazine) {
if (counts.ContainsKey(c)) counts[c]++;
else counts[c] = 1;
}
foreach (char c in ransomNote) {
if (!counts.ContainsKey(c) || counts[c] == 0) return false;
counts[c]--;
}
return true;
}
// Java
public static boolean canConstruct(String ransomNote, String magazine) {
int[] count = new int[26];
for (char c : magazine.toCharArray()) {
count[c - 'a']++;
}
for (char c : ransomNote.toCharArray()) {
if (count[c - 'a'] == 0) return false;
count[c - 'a']--;
}
return true;
}
# Python
def can_construct(ransom_note: str, magazine: str) -> bool:
from collections import Counter
magazine_count = Counter(magazine)
for char in ransom_note:
if magazine_count[char] <= 0:
return False
magazine_count[char] -= 1
return True
Question 2: Find the length of the longest consecutive elements sequence.
Given an unsorted array of integers, return the length of the longest sequence of consecutive numbers.
The sequence must consist of numbers that appear consecutively (e.g., 4, 5, 6, 7), and the numbers do not need to be adjacent in the array.
Your solution should run in O(n) time.
Example Inputs and Outputs
Example 1
Input:
nums = [100, 4, 200, 1, 3, 2]
Output:
4
Explanation:
The longest consecutive sequence is [1, 2, 3, 4].
Example 2
Input:
nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output:
9
Explanation:
The longest consecutive sequence is [0,1,2,3,4,5,6,7,8].
// C#
public static int LongestConsecutive(int[] nums) {
var set = new HashSet<int>(nums);
int longest = 0;
foreach (var num in nums) {
if (!set.Contains(num - 1)) {
int current = num;
int count = 1;
while (set.Contains(++current)) count++;
longest = Math.Max(longest, count);
}
}
return longest;
}
// Java
public static int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) set.add(num);
int longest = 0;
for (int num : nums) {
if (!set.contains(num - 1)) {
int current = num;
int count = 1;
while (set.contains(++current)) count++;
longest = Math.max(longest, count);
}
}
return longest;
}
# Python
def longest_consecutive(nums: list) -> int:
num_set = set(nums)
longest = 0
for num in nums:
if num - 1 not in num_set:
current = num
count = 1
while current + 1 in num_set:
current += 1
count += 1
longest = max(longest, count)
return longest
Question 3: Find the maximum product of three numbers in an array.
You are given an array of integers.
Your task is to return the maximum possible product that can be obtained by multiplying three numbers from the array.
The array may contain:
-
Positive numbers
-
Negative numbers
-
Zero
Note:
The maximum product can come from:
-
The three largest positive numbers, or
-
The two smallest (most negative) numbers and the largest positive number.
Example Inputs and Outputs
Example 1
Input:
nums = [1, 2, 3]
Output:
6
Explanation:
Product = 1 × 2 × 3 = 6.
Example 2
Input:
nums = [-10, -10, 5, 2]
Output:
500
Explanation:
Maximum product is from:
(-10 × -10 × 5) = 500.
// C#
public static int MaxProductOfThree(int[] nums) {
Array.Sort(nums);
int n = nums.Length;
return Math.Max(
nums[n - 1] * nums[n - 2] * nums[n - 3],
nums[0] * nums[1] * nums[n - 1]
);
}
// Java
public static int maxProductOfThree(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
return Math.max(
nums[n-1] * nums[n-2] * nums[n-3],
nums[0] * nums[1] * nums[n-1]
);
}
# Python
def max_product_of_three(nums: list) -> int:
nums.sort()
return max(
nums[-1] * nums[-2] * nums[-3],
nums[0] * nums[1] * nums[-1]
)
Question 4: Find all unique pairs that sum to target.
You are given an array of integers and a target value.
Your task is to return all unique pairs of numbers from the array whose sum equals the target.
Important details:
-
A pair consists of two numbers.
-
Each pair should appear only once, even if the numbers appear multiple times in the array.
-
The order of numbers inside each pair does not matter (e.g.,
(2,5)is the same as(5,2)).
Example Inputs and Outputs
Example 1
Input:
nums = [1, 2, 3, 2, 4, 3]
target = 5
Output:
[(1, 4), (2, 3)]
Explanation:
Pairs that sum to 5:
-
1 + 4
-
2 + 3
Duplicates are removed.
Example 2
Input:
nums = [0, -1, 2, -3, 1]
target = -2
Output:
[(-3, 1)]
// C#
public static List<(int, int)> TwoSumPairs(int[] nums, int target) {
var seen = new HashSet<int>();
var result = new HashSet<(int, int)>();
foreach (var num in nums) {
int complement = target - num;
if (seen.Contains(complement))
result.Add((Math.Min(num, complement), Math.Max(num, complement)));
seen.Add(num);
}
return result.ToList();
}
// Java
public static List<int[]> twoSumPairs(int[] nums, int target) {
Set<Integer> seen = new HashSet<>();
Set<String> resultSet = new HashSet<>();
List<int[]> result = new ArrayList<>();
for (int num : nums) {
int complement = target - num;
if (seen.contains(complement)) {
int min = Math.min(num, complement);
int max = Math.max(num, complement);
String pairKey = min + "," + max;
if (!resultSet.contains(pairKey)) {
resultSet.add(pairKey);
result.add(new int[]{min, max});
}
}
seen.add(num);
}
return result;
}
# Python
def two_sum_pairs(nums: list, target: int) -> list:
seen = set()
result = set()
for num in nums:
complement = target - num
if complement in seen:
pair = tuple(sorted((num, complement)))
result.add(pair)
seen.add(num)
return list(result)
Question 5: Find the missing number in 0 to n sequence.
You are given an array containing n distinct numbers taken from the range 0 to n (inclusive).
Since there are n + 1 total possible numbers but only n numbers in the array, exactly one number is missing.
Your task is to return the missing number.
Example Inputs and Outputs
Example 1
Input:
nums = [3, 0, 1]
Output:
2
Explanation:
Numbers 0–3 are expected.
The array contains {0, 1, 3}, so 2 is missing.
Example 2
Input:
nums = [0, 1]
Output:
2
Explanation:
Sequence is 0–2.
The array lacks 2.
// C#
public static int MissingNumber(int[] nums) {
int n = nums.Length;
int expected = n * (n + 1) / 2;
int actual = nums.Sum();
return expected - actual;
}
// Java
public static int missingNumber(int[] nums) {
int n = nums.length;
int expected = n * (n + 1) / 2;
int actual = 0;
for (int num : nums) actual += num;
return expected - actual;
}
# Python
def missing_number(nums: list) -> int:
n = len(nums)
expected = n * (n + 1) // 2
actual = sum(nums)
return expected - actual
Question 6: Find nth Fibonacci number.
The Fibonacci sequence is defined as:
-
F(0) = 0
-
F(1) = 1
-
For n ≥ 2,
F(n) = F(n-1) + F(n-2)
Your task is to compute the n-th Fibonacci number using an efficient iterative approach (not recursion).
Example Inputs and Outputs
Example 1
Input:
n = 0
Output:
0
Example 2
Input:
n = 1
Output:
1
// C#
public static int FibonacciLoop(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
int f1 = 0, f2 = 1;
for (int i = 2; i <= n; i++) {
int sum = f1 + f2;
f1 = f2;
f2 = sum;
}
return f2;
}
// Java
public static int fibonacci(int n) {
if (n <= 1) return n;
int a = 0, b = 1;
for (int i = 2; i <= n; i++) {
int sum = a + b;
a = b;
b = sum;
}
return b;
}
# Python
def fibonacci(n: int) -> int:
if n <= 1:
return n
a, b = 0, 1
for i in range(2, n + 1):
a, b = b, a + b
return b
Question 7: Calculate factorial of a number.
Given a non-negative integer n, compute its factorial.
The factorial of a number is defined as:
-
0! = 1
-
n! = n × (n−1) × (n−2) × ... × 1
Your task is to calculate n! using an iterative loop.
Example Inputs and Outputs
Example 1
Input:
n = 0
Output:
1
Example 2
Input:
n = 5
Output:
120
Explanation:
5! = 5 × 4 × 3 × 2 × 1 = 120
// C#
public static int FactorialLoop(int n) {
int fact = 1;
for (int i = 2; i <= n; i++) {
fact *= i;
}
return fact;
}
// Java
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
# Python
def factorial(n: int) -> int:
result = 1
for i in range(2, n + 1):
result *= i
return result
Question 8: Merge two sorted arrays into one sorted array.
You are given two sorted integer arrays.
Your task is to merge them into a single sorted array containing all elements from both input arrays.
The final array must be sorted in non-decreasing order.
Example Inputs and Outputs
Example 1
Input:
arr1 = [1, 3, 5]
arr2 = [2, 4, 6]
Output:
[1, 2, 3, 4, 5, 6]
Example 2
Input:
arr1 = [0]
arr2 = [1, 2, 3]
Output:
[1, 2, 3]
// C#
public static int[] MergeTwoSortedArray(int[] arr1, int[] arr2) {
int[] merged = new int[arr1.Length + arr2.Length];
Array.Copy(arr1, merged, arr1.Length);
Array.Copy(arr2, 0, merged, arr1.Length, arr2.Length);
Array.Sort(merged);
return merged;
}
// Java
public static int[] mergeTwoSortedArrays(int[] arr1, int[] arr2) {
int i = 0, j = 0, k = 0;
int[] result = new int[arr1.length + arr2.length];
while (i < arr1.length && j < arr2.length) {
if (arr1[i] <= arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
while (i < arr1.length) result[k++] = arr1[i++];
while (j < arr2.length) result[k++] = arr2[j++];
return result;
}
# Python
def merge_sorted_arrays(arr1: list, arr2: list) -> list:
result = []
i = j = 0
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
result.append(arr1[i])
i += 1
else:
result.append(arr2[j])
j += 1
result.extend(arr1[i:])
result.extend(arr2[j:])
return result
Question 9: Rotate array by k positions.
Given an array arr and an integer k, rotate the array to the right by k positions.
-
Rotating right means each element moves k steps to the right, and elements that “fall off” the end wrap around to the beginning.
-
Use an in-place algorithm (no extra array).
Example Inputs and Outputs
Example 1
Input:
arr = [1, 2, 3, 4, 5, 6, 7]
k = 3
Output:
[5, 6, 7, 1, 2, 3, 4]
Explanation:
Rotate right by 3 steps → last 3 elements move to the front.
Example 2
Input:
arr = [1, 2]
k = 5
Output:
[2, 1]
Explanation:
Rotation uses k % n = 5 % 2 = 1.
// C#
public static int[] RotateArrayByN(int[] arr, int k) {
k %= arr.Length;
ReverseArray(0, arr.Length - 1, arr);
ReverseArray(0, k - 1, arr);
ReverseArray(k, arr.Length - 1, arr);
return arr;
}
private static int[] ReverseArray(int start, int last, int[] arr) {
while (start < last) {
int temp = arr[start];
arr[start] = arr[last];
arr[last] = temp;
start++;
last--;
}
return arr;
}
// Java
public static void rotateArray(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private static void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
# Python
def rotate_array(nums: list, k: int) -> list:
k %= len(nums)
def reverse(start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
reverse(0, len(nums) - 1)
reverse(0, k - 1)
reverse(k, len(nums) - 1)
return nums
Question 10: Find the maximum value in an array.
You are given an array of integers.
Your task is to return the largest (maximum) value contained in the array.
This must be done using a simple linear scan through the array.
Example Inputs and Outputs
Example 1
Input:
arr = [1, 5, 3, 9, 2]
Output:
9
Example 2
Input:
arr = [-2, -8, -3]
Output:
-2
// C#
public static int MaxValueInArray(int[] arr) {
int maxVal = arr[0];
for (int i = 0; i < arr.Length; i++) {
if (arr[i] > maxVal) maxVal = arr[i];
}
return maxVal;
}
// Java
public static int maxValueInArray(int[] arr) {
int max = arr[0];
for (int num : arr) {
if (num > max) max = num;
}
return max;
}
# Python
def max_value_in_array(arr: list) -> int:
max_val = arr[0]
for num in arr:
if num > max_val:
max_val = num
return max_val
Question 11: Find all duplicate numbers in an array.
You are given an array of integers.
Your task is to return all numbers that appear more than once in the array.
Requirements:
-
Return each duplicate number only once.
-
The output should be sorted.
-
Use a HashSet-based approach to track seen numbers efficiently.
Example Inputs and Outputs
Example 1
Input:
arr = [1, 2, 3, 2, 4, 3, 5]
Output:
[2, 3]
Explanation:
Both 2 and 3 appear more than once.
Example 2
Input:
arr = [4, 4, 4, 4]
Output:
[4]
Explanation:
4 is the only duplicate.
// C#
public static int[] DuplicateArrayBySet(int[] arr) {
HashSet<int> uniqueArr = new HashSet<int>();
HashSet<int> duplicates = new HashSet<int>();
foreach (int num in arr) {
if (!uniqueArr.Add(num)) duplicates.Add(num);
}
return duplicates.OrderBy(x => x).ToArray();
}
// Java
public static List<Integer> findDuplicates(int[] nums) {
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();
for (int num : nums) {
if (!seen.add(num)) {
duplicates.add(num);
}
}
return new ArrayList<>(duplicates);
}
# Python
def find_duplicates(nums: list) -> list:
seen = set()
duplicates = set()
for num in nums:
if num in seen:
duplicates.add(num)
else:
seen.add(num)
return list(duplicates)
Question 12: Reverse an array in-place.
Write a function that reverses the elements of an array in-place.
The function should not use extra space for another array.
Sample Inputs and Outputs
Example 1
Input:
arr = [1, 2, 3, 4, 5]
Output:
[5, 4, 3, 2, 1]
Example 2
Input:
arr = [10, 20, 30]
Output:
[30, 20, 10]
// C#
public static int[] ReverseArrayWhile(int[] arr) {
int left = 0, right = arr.Length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr;
}
// Java
public static void reverseArray(int[] arr) {
int left = 0, right = arr.length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
# Python
def reverse_array(arr: list) -> list:
left, right = 0, len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
Question 13: Reverse digits of an integer.
Write a function that reverses the digits of a given integer.
The function should handle positive and negative integers.
Note: Leading zeros in the reversed number should be removed.
Sample Inputs and Outputs
Example 1
Input:
number = 123
Output:
321
Example 2
Input:
number = -456
Output:
-654
// C#
public static int ReverseNumber(int number) {
if (number == 0) return 0;
int reversed = 0;
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
return reversed;
}
// Java
public static int reverseNumber(int num) {
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
return reversed;
}
# Python
def reverse_number(num: int) -> int:
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
return reversed_num
Question 14: Find the maximum sum of contiguous subarray.
Given an integer array, write a function to find the maximum sum of a contiguous subarray.
Return the sum along with the starting and ending indices of the subarray.
This problem can be efficiently solved using Kadane’s Algorithm.
Sample Inputs and Outputs
Example 1
Input:
numbers = [-2,1,-3,4,-1,2,1,-5,4]
Output:
Max sum: 6 (from index 3 to 6)
Explanation: The subarray [4, -1, 2, 1] has the maximum sum 6.
Example 2
Input:
numbers = [1, 2, 3, 4, 5]
Output:
Max sum: 15 (from index 0 to 4)
Explanation: The whole array forms the maximum sum.
// C#
public static void FindMaxSum(int[] numbers) {
if (numbers == null || numbers.Length == 0) {
Console.WriteLine("Array is empty");
return;
}
int currentMax = numbers[0];
int globalMax = numbers[0];
int startIndex = 0, endIndex = 0, tempStart = 0;
for (int i = 1; i < numbers.Length; i++) {
if (numbers[i] > currentMax + numbers[i]) {
currentMax = numbers[i];
tempStart = i;
} else {
currentMax += numbers[i];
}
if (currentMax > globalMax) {
globalMax = currentMax;
startIndex = tempStart;
endIndex = i;
}
}
Console.WriteLine($"Max sum: {globalMax} (from index {startIndex} to {endIndex})");
}
// Java
public static int maxSubArray(int[] nums) {
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for (int i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
# Python
def max_subarray(nums: list) -> int:
max_so_far = max_ending_here = nums[0]
for i in range(1, len(nums)):
max_ending_here = max(nums[i], max_ending_here + nums[i])
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
Question 15: Check if parentheses in string are valid.
Given a string containing only the characters '(', ')', '{', '}', '[' and ']',
write a function to determine if the input string is valid.
A string is valid if:
-
Open brackets are closed by the same type of brackets.
-
Open brackets are closed in the correct order.
Sample Inputs and Outputs
Example 1
Input:
s = "()"
Output:
true
Example 2
Input:
s = "()[]{}"
Output:
true
// C#
public static bool IsValidParentheses(string s) {
Stack<char> stack = new Stack<char>();
Dictionary<char, char> mapping = new Dictionary<char, char> {
{')', '('}, {'}', '{'}, {']', '['}
};
foreach (char c in s) {
if (mapping.ContainsValue(c)) {
stack.Push(c);
} else if (mapping.ContainsKey(c)) {
if (stack.Count == 0 || stack.Pop() != mapping[c]) {
return false;
}
}
}
return stack.Count == 0;
}
// Java
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
Map<Character, Character> mapping = Map.of(')', '(', '}', '{', ']', '[');
for (char c : s.toCharArray()) {
if (mapping.containsValue(c)) {
stack.push(c);
} else if (mapping.containsKey(c)) {
if (stack.isEmpty() || stack.pop() != mapping.get(c)) {
return false;
}
}
}
return stack.isEmpty();
}
# Python
def is_valid_parentheses(s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping.values():
stack.append(char)
elif char in mapping:
if not stack or stack.pop() != mapping[char]:
return False
return len(stack) == 0
Question 16: Check if a string is palindrome.
A palindrome is a string that reads the same forward and backward.
Write a function that determines whether a given string s is a palindrome.
Sample Inputs and Outputs
Example 1
Input:
s = "racecar"
Output:
true
Example 2
Input:
s = "hello"
Output:
false
// C#
public static bool IsPalindrome(string s) {
int left = 0, right = s.Length - 1;
while (left < right) {
if (s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
// Java
public static boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) return false;
left++;
right--;
}
return true;
}
# Python
def is_palindrome(s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
Question 17: Implement binary search.
Write a function that searches for a target value in a sorted array of integers using binary search.
The function should return the index of the target if found, or -1 if the target does not exist in the array.
Sample Inputs and Outputs
Example 1
Input:
nums = [1, 3, 5, 7, 9], target = 5
Output:
2
(5 is at index 2 in the array)
Example 2
Input:
nums = [2, 4, 6, 8, 10], target = 7
Output:
-1
(7 is not in the array)
// C#
public static int BinarySearch(int[] nums, int target) {
int left = 0, right = nums.Length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
// Java
public static int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
# Python
def binary_search(nums: list, target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
Question 18: Find first non-repeating character in string.
Given a string s, write a function to find the first character that does not repeat.
If all characters repeat, return '_'.
Sample Inputs and Outputs
Example 1
Input:
s = "leetcode"
Output:
'l'
Explanation: 'l' is the first character that appears only once.
Example 2
Input:
s = "loveleetcode"
Output:
'v'
Explanation: 'v' is the first non-repeating character.
// C#
public static char FirstNonRepeatingChar(string s) {
Dictionary<char, int> count = new Dictionary<char, int>();
foreach (char c in s) {
if (count.ContainsKey(c)) count[c]++;
else count[c] = 1;
}
foreach (char c in s) {
if (count[c] == 1) return c;
}
return '_';
}
// Java
public static char firstNonRepeatingChar(String s) {
int[] count = new int[256];
for (char c : s.toCharArray()) count[c]++;
for (char c : s.toCharArray()) {
if (count[c] == 1) return c;
}
return '_';
}
# Python
def first_non_repeating_char(s: str) -> str:
from collections import Counter
count = Counter(s)
for char in s:
if count[char] == 1:
return char
return '_'
Question 19: Check if two strings are anagrams.
Given two strings s1 and s2, write a function to determine if they are anagrams of each other.
Two strings are anagrams if they contain the same characters in the same frequency, but the order of characters may differ.
Sample Inputs and Outputs
Example 1
Input:
s1 = "listen"
s2 = "silent"
Output:
true
Example 2
Input:
s1 = "hello"
s2 = "bello"
Output:
false
// C#
public static bool AreAnagrams(string s1, string s2) {
if (s1.Length != s2.Length) return false;
int[] count = new int[26];
foreach (char c in s1) count[c - 'a']++;
foreach (char c in s2) {
if (count[c - 'a'] == 0) return false;
count[c - 'a']--;
}
return true;
}
// Java
public static boolean areAnagrams(String s1, String s2) {
if (s1.length() != s2.length()) return false;
int[] count = new int[26];
for (char c : s1.toCharArray()) count[c - 'a']++;
for (char c : s2.toCharArray()) {
if (count[c - 'a'] == 0) return false;
count[c - 'a']--;
}
return true;
}
# Python
def are_anagrams(s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
from collections import Counter
return Counter(s1) == Counter(s2)
Question 20: Remove duplicates in-place from sorted array.
Given a sorted array, write a function to remove duplicate elements in-place, so that each element appears only once.
Return the new length of the array after duplicates are removed.
Do not allocate extra space for another array; modify the input array in-place.
Sample Inputs and Outputs
Example 1
Input:
nums = [1, 1, 2]
Output:
Length = 2, nums = [1, 2, _]
(The underscore _ represents ignored values beyond the new length.)
Example 2
Input:
nums = [0,0,1,1,1,2,2,3,3,4]
Output:
Length = 5, nums = [0,1,2,3,4,_,_,_,_,_]
// C#
public static int RemoveDuplicates(int[] nums) {
if (nums.Length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.Length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
// Java
public static int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
# Python
def remove_duplicates(nums: list) -> int:
if not nums:
return 0
i = 0
for j in range(1, len(nums)):
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
return i + 1
Comments (0)
No comments yet. Be the first to comment!