We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
defwhatsNext(arr):# set bits are at each even indexl=len(arr)-1# case: l == 0ifnotl:ifarr[0]==1:print(2)print(*[1,1])else:print(3)print(*[1,1,arr[0]-1])return# find index for least significant set biti=l-1ifl&1elsel# case: l == 1ifl==1:t=[1,arr[1]+1,arr[0]-1]# case: last bit group is offelifl-i:t=arr[:i-1]+[arr[i-1]-1,1,arr[-1]+1,arr[i]-1]# case: last bit group is setelse:t=arr[:i-1]+[arr[i-1]-1,1,1,arr[i]-1]# handle zerosifnott[-1]:t.pop(-1)ift.count(0):i_lst=[]fori,ainenumerate(t):ifnota:# combine bits around zerot[i-1]+=t[i+1]i_lst.append(i)# remove zero and extra bitsforiini_lst[-1:-1-len(i_lst):-1]:t.pop(i+1)t.pop(i)print(len(t))print(*t)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
What's Next?
You are viewing a single comment's thread. Return to all comments →
Python 3