LeetCode 1623: All Valid Triplets That Can Represent a Country

Database

Problem Description

Explanation

To solve this problem, we can generate all possible triplets of integers within the given range and check if the triplet satisfies the condition that the sum of the first two numbers is greater than the third number. We can iterate through all combinations of triplets and filter out the valid ones.

Algorithm:

  1. Initialize an empty list to store valid triplets.
  2. Iterate over all possible combinations of triplets in the given range.
  3. For each triplet, check if the sum of the first two numbers is greater than the third number.
  4. If the condition is satisfied, add the triplet to the list of valid triplets.
  5. Return the list of valid triplets.

Time complexity: O(n^3) where n is the range of integers. Space complexity: O(1) excluding the space required to store the output.

Solutions

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<List<Integer>> allValidTriplets(int n) {
        List<List<Integer>> result = new ArrayList<>();
        
        for (int i = 1; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                for (int k = j + 1; k <= n; k++) {
                    if (i + j > k) {
                        List<Integer> triplet = new ArrayList<>();
                        triplet.add(i);
                        triplet.add(j);
                        triplet.add(k);
                        result.add(triplet);
                    }
                }
            }
        }
        
        return result;
    }
}

Loading editor...