Array Subset

Given two arrays: a[] and b[], where both arrays may contain duplicate elements, which are considered as a separate element of the set. Check if array b is a subset of array a.

Hint

Create an empty list or dictionary to keep track of how many times each element appears in list 'a'. Go through each element in list 'b':

# Python implementation
a = [11, 7, 1, 13, 21, 3, 7, 3]
b = [11, 3, 7, 1, 7]
m = {}

output = True

for i in range(len(a)):
  item = a[i]

  if item not in m:
    m[item] = 1
  else:
    m[item] = m[item] + 1

for i in range(len(b)):
  item = b[i]

  if item not in m or m[item] <= 0:
    output = False
    break
  else:
    m[item] = m[item] - 1

print(output)
// Javascript implementation
const a = [11, 7, 1, 13, 21, 3, 7, 3];
const b = [11, 3, 7, 1, 7];
const m = {};

let output = true;

for (let i = 0; i < a.length; i++) {
  let item = a[i];

  if (!m[item]) {
    m[item] = 1;
  } else {
    m[item] = m[item] + 1;
  }
}

for (let i = 0; i < b.length; i++) {
  let item = b[i];

  if (!m[item] || m[item] <= 0) {
    output = false;
    break;
  } else {
    m[item] = m[item] - 1;
  }
}

console.log(output);