712344. Hands of Straights
Hands of Straights
Slug: hands-of-straights
Difficulty: Medium
Id: 712344
Topic Tags: Arrays, Hash, Greedy, Sorting, Data Structures, Algorithms
Company Tags: None
Summary
The "Hands of Straights" problem involves creating a function that takes an array of integers and returns the number of ways to create hands with straights from the given numbers. A hand is considered straight if all the cards have consecutive values. The input array represents the cards in a deck, where each card has a unique value from 1 to 13 (representing Ace to King).
Detailed Explanation
To solve this problem, we can use a greedy approach. First, we sort the input array in ascending order. Then, we initialize a variable straights to keep track of the number of straights found.
Here's the step-by-step breakdown:
- Sort the input array in ascending order.
- Initialize a variable
straightsto 0. - Iterate through the sorted array. For each element:
- If the current card value is consecutive to the previous card value, increment
straights. This means we're finding a straight. - Otherwise, reset the count and start a new straight.
- If the current card value is consecutive to the previous card value, increment
- Return the total number of straights found (
straights).
Here's an ASCII art diagram illustrating the process:
[1, 2, 3, 5, 6] // initial array
[1, 2, 3, 5, 6] // sorted array
straights = 0 // initialize count
iterate through:
card1 = 1 // start with first card
card2 = 2 // consecutive cards found
straights += 1 // increment count
card3 = 3 // consecutive cards found
straights += 1 // increment count
card4 = 5 // reset count, new straight started
straights = 0 // initialize count for new straight
card5 = 6 // consecutive cards found
straights += 1 // increment count
return straights = 2 // total number of straights found
The time complexity for this solution is O(n log n) due to the sorting step, where n is the length of the input array. The space complexity is O(1), as we only use a few variables to keep track of our progress.
Optimized Solutions
Java
public int numberOfHands(int[] cards) {
Arrays.sort(cards);
int straights = 0;
for (int i = 0; i < cards.length - 4; i++) {
if (cards[i] + 4 == cards[i + 4]) {
straights++;
i += 3; // skip the next three consecutive cards
}
}
return straights;
}