679. 24 Game LeetCode Solution

In this guide, you will get 679. 24 Game LeetCode Solution with the best time and space complexity. The solution to Game problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Game solution in C++
  4. Game solution in Java
  5. Game solution in Python
  6. Additional Resources
679. 24 Game LeetCode Solution image

Problem Statement of Game

You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators [‘+’, ‘-‘, ‘*’, ‘/’] and the parentheses ‘(‘ and ‘)’ to get the value 24.
You are restricted with the following rules:

The division operator ‘/’ represents real division, not integer division.

For example, 4 / (1 – 2 / 3) = 4 / (1 / 3) = 12.

Every operation done is between two numbers. In particular, we cannot use ‘-‘ as a unary operator.

For example, if cards = [1, 1, 1, 1], the expression “-1 – 1 – 1 – 1” is not allowed.

You cannot concatenate numbers together

For example, if cards = [1, 2, 1, 2], the expression “12 + 12” is not valid.

Return true if you can get such expression that evaluates to 24, and false otherwise.

Example 1:

Input: cards = [4,1,8,7]
Output: true
Explanation: (8-4) * (7-1) = 24

Example 2:

Input: cards = [1,2,1,2]
Output: false

Constraints:

cards.length == 4
1 <= cards[i] <= 9

Complexity Analysis

  • Time Complexity: O(2^n), where n = 4
  • Space Complexity: O(2^n)

679. 24 Game LeetCode Solution in C++

class Solution {
 public:
  bool judgePoint24(vector<int>& nums) {
    vector<double> doubleNums;

    for (const int num : nums)
      doubleNums.push_back(num);

    return dfs(doubleNums);
  }

 private:
  bool dfs(vector<double>& nums) {
    if (nums.size() == 1)
      return abs(nums[0] - 24) < 0.001;

    for (int i = 0; i < nums.size(); ++i)
      for (int j = 0; j < i; ++j) {
        for (const double num : generate(nums[i], nums[j])) {
          vector<double> nextRound{num};
          for (int k = 0; k < nums.size(); ++k) {
            if (k == i || k == j)  // It is used in `generate()`.
              continue;
            nextRound.push_back(nums[k]);
          }
          if (dfs(nextRound))
            return true;
        }
      }

    return false;
  }

  vector<double> generate(double a, double b) {
    return {a * b, a / b, b / a, a + b, a - b, b - a};
  }
};
/* code provided by PROGIEZ */

679. 24 Game LeetCode Solution in Java

class Solution {
  public boolean judgePoint24(int[] nums) {
    List<Double> doubleNums = new ArrayList<>();

    for (final int num : nums)
      doubleNums.add((double) num);

    return dfs(doubleNums);
  }

  private boolean dfs(List<Double> nums) {
    if (nums.size() == 1)
      return Math.abs(nums.get(0) - 24.0) < 0.001;

    for (int i = 0; i < nums.size(); ++i)
      for (int j = i + 1; j < nums.size(); ++j)
        for (final double num : generate(nums.get(i), nums.get(j))) {
          List<Double> nextRound = new ArrayList<>(List.of(num));
          for (int k = 0; k < nums.size(); ++k) {
            if (k == i || k == j) // It is used in `generate()`.
              continue;
            nextRound.add(nums.get(k));
          }
          if (dfs(nextRound))
            return true;
        }

    return false;
  }

  private double[] generate(double a, double b) {
    return new double[] {a * b, a / b, b / a, a + b, a - b, b - a};
  }
}
// code provided by PROGIEZ

679. 24 Game LeetCode Solution in Python

class Solution:
  def judgePoint24(self, nums: list[int]) -> bool:
    def generate(a: float, b: float) -> list[float]:
      return [a * b,
              math.inf if b == 0 else a / b,
              math.inf if a == 0 else b / a,
              a + b, a - b, b - a]

    def dfs(nums: list[float]) -> bool:
      if len(nums) == 1:
        return abs(nums[0] - 24.0) < 0.001

      for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
          for num in generate(nums[i], nums[j]):
            nextRound = [num]
            for k in range(len(nums)):
              if k == i or k == j:
                continue
              nextRound.append(nums[k])
            if dfs(nextRound):
              return True

      return False

    return dfs(nums)
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.