Interview Question- String subsequence challenge

I want to find the minimum subsequence. Have I done this correctly or how can it be better? thank you.

Iā€™m not sure I completely understand the objective here? Could you give a little more detail on what this function is supposed to be doing?

determine if primary is a subsequence of secondary

Primary: AB
Secondary: ABC
False

Primary: AB
Secondary: ABAB
True

Primary: ABAB
Secondary: ABABAB
False

If primary is a subsequence of secondary return the minimum of primary that is a subsequence

Primary: ABAB
Secondary: ABABABAB
minimum subsequence: AB

if primary is not a subsequence return negative length of secondary

Ah, I would try to simplify your code. I see this as two phases

  1. can the second string be made by repeating the first?
  2. is there any substring of the first that can recreate the first?

I think you can use the function itself to check 2.

Here is a guess at what might work
function findSmallestRepeatedSubsequence(first, second) {
  // Check if the second can evenly hold
  //  multiples of the first
  if (second.length % first.length !== 0)
    return false;
  // Check for repetition of first
  for (let i = 0; i < second.length; i += first.length)
    if (second.substring(i, i + first.length) != first)
      return false;
  // Check if smaller subseq will work
  for (let i = 1; i <= first.length/2; i++)
    if (findSmallestRepeatedSubsequence(first.substring(0, i), first))
      return first.substring(0, i);
  // No smaller subseq of first will work
  return first;
}
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.