Top 10 Programming Languages to Learn in 2019

CodeChef's Solutions

Flipping Coins Solution with Approach – Codechef Page Contents

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”.

Input

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

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

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 :
0
1
0
2
1

Constraints

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

Solution

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.

Approach

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.

Code

import numpy as np
import sys

# Using sys.stdin.readline() since it is fast
# 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]
else:
print(L[x:y+1].sum())

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.