Print Even - Odd in Python (Time Complexity: O(n))


Given a positive integer n, for each number from 0 to n - 1, print "odd" if the number is odd or the number itself if it is even.

Example:

Input: n = 6
Output (console):
0
odd
2
odd
4
odd

Note:

You have to print to the console, your function shouldn't return anything.

Understanding the Problem

The core challenge of this problem is to iterate through a range of numbers and determine whether each number is odd or even. If the number is odd, we print "odd"; if it is even, we print the number itself. This problem is straightforward but helps in understanding basic control structures and conditional statements in Python.

Approach

To solve this problem, we can use a simple loop to iterate through the numbers from 0 to n-1. For each number, we check if it is odd or even using the modulus operator (%). If the number is odd (i.e., number % 2 != 0), we print "odd". Otherwise, we print the number itself.

Naive Solution

The naive solution involves iterating through each number and using an if-else statement to check if the number is odd or even. This approach is already optimal for this problem since it runs in O(n) time complexity, where n is the input number.

Optimized Solution

Given the simplicity of the problem, the naive solution is already optimal. There are no further optimizations needed for this specific problem.

Algorithm

  1. Start a loop from 0 to n-1.
  2. For each number, check if it is odd or even using the modulus operator (%).
  3. If the number is odd, print "odd".
  4. If the number is even, print the number itself.

Code Implementation

def print_even_odd(n):
    # Iterate through each number from 0 to n-1
    for i in range(n):
        # Check if the number is odd
        if i % 2 != 0:
            print("odd")
        else:
            print(i)

# Example usage
n = 6
print_even_odd(n)

Complexity Analysis

The time complexity of this solution is O(n) because we are iterating through each number from 0 to n-1 exactly once. The space complexity is O(1) as we are not using any additional space that scales with the input size.

Edge Cases

Some potential edge cases include:

These edge cases are handled naturally by the loop and conditional statements.

Testing

To test the solution comprehensively, consider the following test cases:

Thinking and Problem-Solving Tips

When approaching such problems, it's important to:

Conclusion

In this blog post, we discussed how to solve the problem of printing "odd" for odd numbers and the number itself for even numbers within a given range. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems helps in building a strong foundation in programming and problem-solving skills.

Additional Resources

For further reading and practice, consider the following resources: