Katkat

Print all odd numbers from an integer list

AmazonSoftware Engineer · Technical Screen

Last updated

This question tests the ability to filter a collection based on a parity condition and handle potential overflow or negative integer scenarios.

Problem Statement

Given a list of integers, return a new list containing only the odd numbers from the original list, maintaining their relative order. You must handle both positive and negative integers.

Function Signature

def get_odd_numbers(nums: List[int]) -> List[int]:

Constraints

  • 0 <= len(nums) <= 10^5
  • -2^63 <= nums[i] <= 2^63 - 1

Examples

Example 1: Input: nums = [1, 2, 3, 4, 5] Output: [1, 3, 5] Explanation: Only 1, 3, and 5 are odd numbers.

Example 2: Input: nums = [-3, -2, -1, 0, 1] Output: [-3, -1, 1] Explanation: Negative numbers are included; -3 and -1 are odd because they are not divisible by 2.

Edge Cases

  • Empty input list.
  • A list containing only even numbers.
  • Large integers (ensure the modulo operator handles negative numbers correctly in your chosen language).

Hints

Hint 1

A number is odd if the remainder when divided by 2 is not zero.

Hint 2

Be careful with the modulo operator (%) on negative numbers in some languages; ensure your logic correctly identifies -1 as odd.

Hint 3

You can use a list comprehension or a standard for-loop to iterate through the input and build the result list.

Follow-up questions

  • How would you modify this function to return only unique odd numbers?
  • What is the time and space complexity of your solution, and can it be optimized?
  • How would you handle the input if the list was so large that it could not fit into memory, and you instead received an iterator?