DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Subsequence-Get All Subsequnce + Get All strictly increasing Subsequnce

All strictly increasing Subsequnce

// JavaScript program for the above approach

// Find all subsequences of string
const getSubsequence = (input) => {
  let results = [];
  const printSubsequence = (input, output) => {
    // Base Case
    // if the input is empty print the output string
    if (input.length == 0) {
      results.push(output);
      return;
    }
    // output is passed with including the Ist character ofInput string
    printSubsequence(input.substring(1), output + input[0]);
    // output is passed without including the Ist character of Input string
    printSubsequence(input.substring(1), output);
  };

  printSubsequence(input, "");
  return results;
};

console.log(getSubsequence("ab"));
console.log(getSubsequence("312"));

// Find all subsequences of Array - also called as subsets
const getSubsequenceOfArray = (arr) => {
  let results = [];
  const printSubsequence = (tempArray, index) => {
    if (index >= arr.length) {
      results.push([...tempArray]);
      return;
    }
    printSubsequence([...tempArray, arr[index]], index + 1);
    printSubsequence([...tempArray], index + 1);
  };

  printSubsequence([], 0);
  return results;
};

console.log(getSubsequenceOfArray([1, 2, 3]));

Enter fullscreen mode Exit fullscreen mode

Strictly Increasing Subsequence


/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var findSubsequences = function (nums) {
  let result = [];
  const set = new Set();

  const getSubsequence = (tempArray, index) => {
    if (index === nums.length) {
      if (tempArray.length > 1) {
        let tempJoin = [...tempArray]?.join("-");
        if (!set.has(tempJoin)) {
          set.add(tempJoin);
          result.push([...tempArray]);
        }
      }
      return;
    }

    if (!tempArray.length || tempArray[tempArray.length - 1] <= nums[index]) {
      getSubsequence([...tempArray, nums[index]], index + 1);
    }
    getSubsequence(tempArray, index + 1);
  };
  getSubsequence([], 0);

  return result;
};

console.log(findSubsequences([1, 2, 3]));
console.log(findSubsequences([4, 6, 7, 7]));
console.log(findSubsequences([4, 4, 3, 2, 1]));

Enter fullscreen mode Exit fullscreen mode

Top comments (0)