DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Subset vs Substring

SubString

-extracts characters, between two indices (positions), from a string, and returns the substring.

var theString = "abc",
  allSubstrings = [];

getAllSubstrings(theString);

function getAllSubstrings(str) {
  for (let i = 0; i < str.length; i++) {
    for (let j = i + 1; j <= str.length; j++) {
      allSubstrings.push(str.substring(i, j));
    }
  }
}

console.log(allSubstrings);
Enter fullscreen mode Exit fullscreen mode

[ 'a', 'ab', 'abc', 'b', 'bc', 'c' ] - Please note 'ac' is not a substring.

Subset

-A subset MAY NOT maintain relative ordering of elements and can or cannot be a contiguous part of an array. For a set of size n, we can have (2^n) sub-sets in total.

var subsets = function (str) {
  let index = 0;
  let subset = [];
  let current = "";
  findSubset(index, str, subset, current);
  return subset;
};

const findSubset = (index, str, subset, current) => {
  if (index === str?.length) {
    subset.push(current);
    return;
  }

  findSubset(index + 1, str, subset, current + str.charAt(index));
  findSubset(index + 1, str, subset, current);
};

console.log(subsets("abc"));

Enter fullscreen mode Exit fullscreen mode

[ 'a', 'ab', 'abc', 'b', 'bc', 'c' ] - Please note 'ac' & '' is subset

Top comments (0)