# Hackerrank: Sherlock and the Valid String Solution

## Approach

Build 2 hash map of

• occurence of character
• occurence of occurence

Work on the hash map of occurence of occurence

• always
YES
if the hash map size is 1
• always
NO
if the hash map size is different from 2

With case of hash map size of 2

• always
YES
if one of the pair is
[1, 1]
• always
YES
if one pair's value is one and subtract of its key and the other is 1
• the rest is
NO

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}function isValid(s) {2  const charOccMap = new Map()3  const occOccMap = new Map()4  s.split("").forEach(c => charOccMap.set(c, (charOccMap.get(c) || 0) + 1))5  Array.from(charOccMap.values()).forEach(occ =>6    occOccMap.set(occ, (occOccMap.get(occ) || 0) + 1)7  )8
9  if (occOccMap.size === 1) {10    return "YES"11  }12  if (occOccMap.size !== 2) {13    return "NO"14  }15  const validPairCase1 = (pair1, pair2) =>16    pair1[1] === 1 && pair1[0] - pair2[0] === 117  const validPairCase2 = (pair1, pair2) =>18    (pair1[0] === 1 && pair1[1] === 1) || (pair2[0] === 1 && pair2[1] === 1)19  const [occX, occY] = Array.from(occOccMap)20  return validPairCase1(occX, occY) ||21    validPairCase1(occY, occX) ||22    validPairCase2(occX, occY)23    ? "YES"24    : "NO"25}```

hackerrank

string

## Next Post

Hackerrank: Mark and Toys

Jan 28, 2021

Search Posts