Top 10 Programming Languages to Learn in 2019

CodeChef's Solutions

Flipping Coins Solution with Approach – Codechef

code-chef's solution

Problem Statement

There are N coins kept on the table, numbered from 0 to N – 1. Initially, each coin is kept tails up. You have to perform two types of operations:

  1. Flip all coins numbered between A and B inclusive. This is represented by the command “0 A B”
  2. Answer how many coins numbered between A and B inclusive are heads up. This is represented by the command “1 A B”.


The first line contains two integers, N and Q. Each of the next Q lines are either of the form “0 A B” or “1 A B” as mentioned above.


Output 1 line for each of the queries of the form “1 A B” containing the required answer for the corresponding query.

Sample Input/Output

Sample Input : 
4 7
1 0 3
0 1 2
1 0 1
1 0 0
0 0 3
1 0 3
1 3 3

Sample Output :


1 <= N <= 100000 
1 <= Q <= 100000
0 <= A <= B <= N - 1


It is a Simple problem related to fast input/ output processing. Key to this problem is using sys.stdin module instead of the default input() function.


  1. Initialize a Numpy array with N number of zeroes.
  2. For the value of p == 0. use negation to reverse the values in the array.
  3. For p == 1, Calulate the sum and print it.


import numpy as np
import sys

# Using sys.stdin.readline() since it is fast
N,M = map(int,sys.stdin.readline().split())
# Initializing the Numpy Array
L = np.zeros(N, dtype=bool)
for _ in range(M):
    p,x,y = map(int, sys.stdin.readline().split())

    if p == 0:
        L[x:y+1] = ~L[x:y+1]

This code uses bitwise operators for speedy calculations. Bitwise operators can make you competitive life easy. Take our Quick Guide on bitwise operators to know more.

Related posts
CodeChef's Solutions

Number of Factors Solution with Approach - CodeChef

CodeChef's Solutions

The Next Palindrome's Solution with Approach - CodeChef

CodeChef's Solutions

Marbles' Solution with Approach - Codechef

CodeChef's Solutions

Closing the Tweets Problem's Solution with Approach - CodeChef

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.