Similar Problems

Similar Problems not available

Three Consecutive Odds - Leetcode Solution

Companies:

LeetCode:  Three Consecutive Odds Leetcode Solution

Difficulty: Easy

Topics: array  

Problem Statement:

Given an integer n, return an array containing n unique integers such that they add up to 0. The integers must be in ascending order, and there must be exactly three integers that are consecutive odds.

Solution:

To solve this problem, we need to break it down into smaller problems.

  1. Generate n unique integers that sum up to 0.
  2. Find three consecutive odd integers in the set.

Step 1: Generate n unique integers that sum up to 0

To generate n unique integers that sum up to 0, we can start by generating n-1 integers randomly. We can then calculate the sum of these n-1 integers and the negation of this sum will be our nth integer. This will ensure that the sum of all n integers is zero.

Algorithm:

  1. Create an empty list nums.
  2. Generate n-1 random integers and append to nums.
  3. Calculate the sum of the n-1 integers in nums.
  4. Append the negation of the sum to nums.
  5. Return nums.

Python implementation of Step 1:

import random

def generate_nums(n):
    nums = []
    for i in range(n-1):
        nums.append(random.randint(-100, 100))
    nums.append(-sum(nums))
    return nums

Step 2: Find three consecutive odd integers in the set

To find three consecutive odd integers in the set, we can iterate over the list of integers and check if we encounter three consecutive odd integers. If we do, we return those integers as a list.

Algorithm:

  1. Create a list odds to store consecutive odd integers.
  2. Iterate over the list nums and check if the integer is odd.
  3. If the integer is odd, append it to odds.
  4. If the length of odds is greater than 3, remove the first element of odds.
  5. If the length of odds is 3 and all elements are consecutive, return odds.
  6. If we reach the end of nums and haven't found three consecutive odd integers, return an empty list.

Python implementation of Step 2:

def find_consecutive_odds(nums):
    odds = []
    for n in nums:
        if n % 2 == 1:
            odds.append(n)
            if len(odds) > 3:
                odds.pop(0)
            if len(odds) == 3 and odds[0]+2 == odds[1]+1 == odds[2]:
                return odds
    return []

Putting it all together:

class Solution:
    def threeConsecutiveOdds(self, n: int) -> List[int]:
        nums = generate_nums(n)
        odds = find_consecutive_odds(nums)
        return odds

Time Complexity:

Generating n-1 random integers takes O(n) time. Checking if an integer is odd and appending it to a list takes O(1) time. Removing the first element of a list also takes O(1) time. Thus, the time complexity of our algorithm is O(n).

Space Complexity:

We are storing n integers in the nums list and at most 3 integers in the odds list. Thus, the space complexity of our algorithm is O(n).

Three Consecutive Odds Solution Code

1