1 ) Finding the longest palindromic substring
Java Solution
Time O(n^2) Space O(1)
Time O(n^2) Space O(1)
2) Remove Duplicates from Sorted Array (Java)
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2],
Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
Java Solution
public int removeDuplicates(int[] A) {
if (A.length < 2)
return A.length;
int j = 0;
int i = 1;
while (i < A.length) {
if (A[i] == A[j]) {
i++;
} else {
A[++j] = A[i++];
}
}
return j + 1;
}
(b) What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],
Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3].
Java Solution
public int removeDuplicates(int[] A) {
if (A.length <= 2)
return A.length;
int prev = 1; // point to
previous
int curr = 2; // point to current
while (curr < A.length) {
if (A[curr] == A[prev]
&& A[curr] == A[prev - 1]) {
curr++;
}
else {
prev++;
A[prev]
= A[curr];
curr++;
}
}
return prev + 1;
}
3) Permutations (Java)
Given a collection of numbers, return all possible permutations.
For example, [1,2,3] have the following permutations: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
Java solution using Recursion. Swap each element with each element after it.
all possible permutations in case of duplicate allowJava solution using Recursion. Swap each element with each element after it.
No comments:
Post a Comment