Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
HAPPY CASE
Input: nums = [2,1,3,3], k = 2
Output: [3,3]
Explanation:
The subsequence has the largest sum of 3 + 3 = 6.
Input: nums = [-1,-2,3,4], k = 3
Output: [-1,3,4]
Explanation:
The subsequence has the largest sum of -1 + 3 + 4 = 6.
EDGE CASE
Input: nums = [-199], k = 1
Output: [-199]
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Array problems, we want to consider the following approaches:
⚠️ Common Mistakes
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Collect the numbers in index pairs. Select the largest k numbers. Return the k largest numbers as sorted by index.
1. Hashmap/Tuple number in sorted index pairs.
2. Select the largest k numbers
3. Sort largest k numbers by index
4. Return the k largest numbers as sorted by index.
Implement the code to solve the algorithm.
class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
# Hashmap/Tuple number in sorted index pairs.
sortedNumAndIndexByNum = [[num,i] for i, num in enumerate(nums)]
sortedNumAndIndexByNum.sort(key=lambda x:x[0])
# Select the largest k numbers
sortedSubsequenceByIndex = sortedNumAndIndexByNum[len(nums)-k:]
# Sort largest k numbers by index
sortedSubsequenceByIndex.sort(key=lambda x:x[1])
# Return the k largest numbers as sorted by index.
return [numAndIndex[0] for numAndIndex in sortedSubsequenceByIndex]
class Solution {
public int[] maxSubsequence(int[] nums, int k) {
// Hashmap/Tuple number in sorted index pairs.
PriorityQueue<int[]> q = new PriorityQueue<>((a,b)-> (a[0]-b[0]));
// Select the largest k numbers
for(int i=0; i<nums.length; i++)
{
q.offer(new int[]{nums[i],i});
if(q.size()> k)
{
q.poll();
}
}
// Sort largest k numbers by index
Set<Integer> index = new HashSet<>();
while(!q.isEmpty())
{
int[] top = q.poll();
index.add(top[1]);
}
// Return the k largest numbers as sorted by index.
int[] result = new int[k];
int p =0;
for(int i=0; i< nums.length; i++)
{
if(index.contains(i))
{
result[p] = nums[i];
++p;
}
}
return result;
}
}
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of items in the array.
O(NlogN)
because we needed to use sort to collect the numbers ascending by value and then by index.O(N)
because we needed to create a hashmap/tuple pair of numbers and index.