Home > Back-end >  delete character of 2 string to make them anagram in typescript
delete character of 2 string to make them anagram in typescript

Time:11-05

I tried to solve one of the Hackerrank challenges String: Making Anagrams

I have 2 strings like this:

let a: string = "fcrxzwscanmligyxyvym"
let b: string = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"

and I have a function that only passed 3 tests!!! :

function makeAnagram(a: string, b: string): number {
    type Map = {
        [key :string] : number
    }
   let string1 = a.split('')
   let string2 = b.split('')
   let map : Map = {}
   let deletedCount = 0
   let firstCount = 0
   let isMoreThanTwo = false
   
   for(let i of string1) {
       map[i] = (map[i] | 0)   1
   }
   
   for(let i of string2){
       map[i] = (map[i] | 0)   1
   }
   
   for(let i in map) {
       if(map[i] == 1) {
           deletedCount  
           firstCount  
       } else if(map[i] > 2) {
           isMoreThanTwo = true
           deletedCount  = (map[i] - 1)
       }
       
   }
   
   return isMoreThanTwo ? deletedCount   firstCount : deletedCount

is there any other solution to count deleted characters? and can you guys give me some advice, thank you

CodePudding user response:

I've just solved this problem but before passing all test cases I came to a solution where I used

for (let [k, v] of map) {
  remain  = v;
}

which failed 13/16 test cases, then I debugged the program and came to know that sometimes when we subtract 1 from the previous of this step, It goes less than 0 so Yo also have to handle this case, I handles as

for (let [k, v] of map) {
  remain  = v < 0 ? v * -1 : v;
}

Now, all test cases are passed

function makeAnagram(a, b) {
  const [small, big] = a.length < b.length ? [a, b] : [b, a];
  const map = new Map();
  for (let c of small) {
    map.set(c, (map.get(c) ?? 0)   1);
  }

  let remain = 0;
  for (let c of big) {
    !map.has(c) ? remain   : map.set(c, map.get(c) - 1);
  }

  for (let [k, v] of map) {
    remain  = v < 0 ? v * -1 : v;
  }

  return remain;
}

console.log(makeAnagram("fast", "sofasty"));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related