Try to search your question here, if you can't find : Ask Any Question Now ?

# 'Terminated due to timeout'

HomeCategory: stackoverflow'Terminated due to timeout'

Why this code is showing ‘Terminated due to timeout‘ on Hackerrank ?

I’m trying to do a task at Day 29: Bitwise AND in ‘30 days of code‘ on Hackerrank. Here is the task:

Given set S = {1,2,3,…N}. Find two integers, A and B (where A < B), from set S such that the value of A & B is the maximum possible and also less than a given integer, K. In this case, & represents the bitwise AND operator.

Input Format

The first line contains an integer, T, the number of test cases. Each of the T subsequent lines defines a test case as 2
space-separated integers, N and K, respectively.

Constraints

1 <= T <= 10^3
2 <= N <= 10^3
2 <= K <= N

Output Format

For each test case, print the maximum possible value of A & B on a new line.

Sample Input

3

5 2

8 5

2 2

Sample Output

1

4

0

Explanation

N = 5, K = 2, S = {1,2,3,4,5}

All possible values of and are:

1. A = 1, B = 2; A & B = 0
2. A = 1, B = 3; A & B = 1
3. A = 1, B = 4; A & B = 0
4. A = 1, B = 5; A & B = 1
5. A = 2, B = 3; A & B = 2
6. A = 2, B = 4; A & B = 0
7. A = 2, B = 5; A & B = 0
8. A = 3, B = 4; A & B = 0
9. A = 3, B = 5; A & B = 1
10. A = 4, B = 5; A & B = 4

The maximum possible value of A&B that is also < (K = 2) is 1, so we print 1 on a new line.

Here is my code:

``````import math
import os
import random
import re
import sys

if __name__ == '__main__':

for t_itr in range(t):

n = int(nk[0])

k = int(nk[1])

lst1 = [(a, b) for a in range(1, n + 1) for b in range(a + 1, n + 1)]

lst2 = [ a & b for (a,b) in lst1 if a & b < k]

print(max(lst2))
``````

This task has total 6 test cases, in test case 1 and 2, my code is True, but in 4 next test cases, it raise: ‘Terminated due to timeout‘.

Can you explain for me what am I wrong ? And what can I do to finish all the test cases? Thanks for helping me !