Showing posts with label Problem solving. Show all posts
Showing posts with label Problem solving. Show all posts

Friday, April 21, 2023

Bitwise AND in Python

 



import math
import os
import random
import re
import sys

from collections import defaultdict

#
# Complete the 'countPairs' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#

def countPairs(arr):
    po2 = lambda x: x > 0 and not (x & (x - 1))
    d = defaultdict(int)
    for x in arr:
        d[x] += 1
    d = list(d.items())
    ans = 0
    for i in range(len(d)):
        a, a_cnt = d[i]
        for j in range(i, len(d)):
            b, b_cnt = d[j]
            if po2(a & b):
                if a == b:
                    ans += (a_cnt * (a_cnt - 1)) // 2
                else:
                    ans += a_cnt * b_cnt
    return ans          

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    arr_count = int(input().strip())

    arr = []

    for _ in range(arr_count):
        arr_item = int(input().strip())
        arr.append(arr_item)

    result = countPairs(arr)

    fptr.write(str(result) + '\n')

    fptr.close()

Task of Pairing

 





#!/bin/python3

import math
import os
import random
import re
import sys



#
# Complete the 'taskOfPairing' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts LONG_INTEGER_ARRAY freq as parameter.
#

def taskOfPairing(freq):
    # Initialize the start of the continuous subarray
    i_0 = 0
    # Initialize the end of the continuous subarray
    i_1 = 1
    n = len(freq)
    total = 0

    while i_1 < n:
        # While not at the end of the subarray, check if the next value is non-zero
        if freq[i_1] == 0:
            # If value is zero, take the sum of the continuous subarray and integer divide by 2. That's the
            # number of pairs in this segment
            total += sum(freq[i_0: i_1]) // 2
            # The new start of the continuous array is here
            i_0 = i_1
        i_1 += 1
    # Upon reaching the end, find the number of pairs of the last subarray
    total += sum(freq[i_0:i_1]) // 2
    return total
    
            
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    freq_count = int(input().strip())

    freq = []

    for _ in range(freq_count):
        freq_item = int(input().strip())
        freq.append(freq_item)

    result = taskOfPairing(freq)

    fptr.write(str(result) + '\n')

    fptr.close()

Longest Subarray in python

 








#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'longestSubarray' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def longestSubarray(arr):
n = len(arr)
ans = 0
# O(n^2) is okay because of constraints.
for i in range(n):
w = []
cnt = 0
for j in range(i, n):
if arr[j] in w:
cnt += 1
continue
if len(w) == 0:
w.append(arr[j])
elif len(w) == 1:
if abs(w[0] - arr[j]) > 1:
break
else:
w.append(arr[j])
else:
break
cnt += 1
ans = max(ans, cnt)
return ans
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr_count = int(input().strip())
arr = []
for _ in range(arr_count):
arr_item = int(input().strip())
arr.append(arr_item)
result = longestSubarray(arr)
fptr.write(str(result) + '\n')
fptr.close()

Username Changes in Python

 

                                                      A company has released a new internal system, and each employee has been assigned a username. Employees are allowed to change their usernames but only in a limited way. More specifically, they can choose letters at two different positions and swap them. For example, the username “bigfish” can be changed to “gibfish” (swapping ‘b’ and ‘g’) or “bighisf” (swapping ‘f’ and ‘h’). The manager would like to know which employees can update their usernames so that the new username is smaller in alphabetical order than the original username.
For each username given, return either “YES” or “NO” based on whether that username can be changed (with one swap) to a new one that is smaller in alphabetical order. Usernames changes certification test problem | Hackerrank Solution
Note: For two different strings A and B of the same length, A is smaller than B in alphabetical order when on the first position where A and B differ, A has a smaller letter in alphabetical order than B has.

For example 


let’s say usernames = [“bee”, “superhero”, “ace”]. For the first username, “bee”, it is not possible to make one swap to change it to a smaller one in alphabetical order, so the answer is “NO”. For the second username, “superhero”, it is possible get a new username that is smaller in alphabetical order (for example, by swapping letters ‘s’ and ‘h’ to get “hupersero”), so the answer is “YES”. Finally, for the last username “ace”, it is not possible to make one swap to change it to a smaller one in alphabetical order, so the answer is “NO”. Therefore you would return the array of strings [“NO”. “YES”, “NO”].

Function Description


Complete the function possibleChanges in the editor below.
possible Changes has the following parameter(s): string usernames[n] an array of strings denoting the usernames of the employees Returns:
string[n]: an array of strings containing either “YES” or “NO” based on whether the username can be changed with one swap to a new one that is smaller in alphabetical order











#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'possibleChanges' function below.
#
# The function is expected to return a STRING_ARRAY.
# The function accepts STRING_ARRAY usernames as parameter.
#
def possibleChanges(usernames):
ans = []
for u in usernames:
if len(u) <= 1:
ans.append("NO")
for i in range(len(u) - 1):
if u[i] > u[i + 1]:
ans.append("YES")
break
else:
ans.append("NO")
return ans
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
usernames_count = int(input().strip())
usernames = []
for _ in range(usernames_count):
usernames_item = input()
usernames.append(usernames_item)
result = possibleChanges(usernames)
fptr.write('\n'.join(result))
fptr.write('\n')
fptr.close()

Featured Post

14. Longest Common Prefix

Popular Posts