DEV Community

OlumideSamuel
OlumideSamuel

Posted on

6 2

Winning Card (DSA Series)

Problem

Winning Card
In a card game, each player will be given a set of random cards. Players will throw on the table their one winning card, the player with the highest card wins.

A winning card is the card that only exists once in the set of cards, and the highest one.

Given an array of sets of integers cards, return the card of the winning player. Return -1 If no such card is found.

  • Example 1:
  • Input: cards = [[5,7,3,9,4,9,8,3,1], [1,2,2,4,4,1], [1,2,3]]
  • Output: 8

  • Example 2:

  • Input: cards = [[5,5], [2,2]]

  • Output: -1

Solution

  • Loop through the 2 dimensional array,
  • On second loop, if item exist in hashset, delete prev occurence of i. Else add to hashset
  • loop through hashset for the highest number
function winningCard(multiArray) {
    let map = new Set();
    multiArray.forEach(item => {
        for (let i = 0; i < item.length; i++) {
            if (map.has(item[i])) {
               map.delete(item[i])
            } else map.add(item[i])
        }
    })

    if (map.size === 0) return -1;

    let highest = 0;
    for (let i of map) {
        if(i > highest) {
            highest = i
        }
    }

   return highest;
}
Enter fullscreen mode Exit fullscreen mode

Anyway, if you have a better way of solving this, you can drop your solution in the comments. I'm no expert. Just learning aloud.

Don't forget to like, share and drop a comment. :)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay