Game of Thrones - I

  • + 0 comments

    JavaScript solution with detailed comments:

    function countOccurrences(arr) {
      const occurrences = {}; // Create an empty object to store element occurrences
    
      for (let i = 0; i < arr.length; i++) { // Iterate through each element in the array
        const element = arr[i]; // Get the current element
    
        if (occurrences[element]) { // If the element already exists as a key in occurrences
          occurrences[element] += 1; // Increment the count for that element by 1
        } else { // If the element doesn't exist as a key in occurrences
          occurrences[element] = 1; // Create a new key for the element with an initial count of 1
        }
      }
    
      return occurrences; // Return the occurrences object
    }
    
    function checkPalindrome(text) {
        let numberOfUnevenWords = 0; // Initialize a counter for the number of unevenly occurring characters
    
        const textArr = text.split('').sort(); // Convert the input text into an array of characters and sort it
    
        const countObj = countOccurrences(textArr); // Count the occurrences of each character using the countOccurrences function
    
        for (let key in countObj) { // Iterate over each unique character in the countObj
            numberOfUnevenWords += countObj[key] % 2; // Increment the numberOfUnevenWords if the count of the character is odd
        }
    
        return numberOfUnevenWords <= 1; // Return true if the numberOfUnevenWords is less than or equal to 1, indicating a palindrome
    }
    
    /*
     * Complete the 'gameOfThrones' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts STRING s as parameter.
     */
    
    function gameOfThrones(s) {
        // Write your code here
        const isPalindrome = checkPalindrome(s)
        return isPalindrome ? 'YES' : 'NO'
    }