Manipulative Numbers – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
Solutions of Algorithms Data Structures Hard HackerRank:
Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
C++ replace HackerRank Solution
#include <cstdio>
#include <iostream>
#include <cmath>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <complex>
#include <algorithm>
#include <functional>
#include <fstream>
#include <numeric>
#include <string>
#include <valarray>
#define int long long
using namespace std;
typedef pair<int,int> Pair;
template<class t>
ostream & operator << (ostream & tout,const vector<t> &s){
tout<<'[';
for (int i=0;i<s.size();i++)
if (i+1 == s.size())
tout<<s[i];
else
tout<<s[i]<<',';
tout<<']';
return(tout);
}
template<class a,class b>
ostream & operator << (ostream & tout,const pair<a,b> &c){
return(tout<<'('<<c.first<<','<<c.second<<')');
}
template<class T> struct __set__print{
__set__print(ostream& out) : tout(out), count(0) {}
void operator() (T x) {
if (count > 0)
tout<<',';
tout<<x;
++count;
}
ostream& tout;
int count;
};
template<class T>
ostream & operator << (ostream & tout,const set<T> &s){
tout<<'{';
for_each(s.begin(),s.end(),__set__print<T>(tout));
return(tout<<'}');
}
template<class T,class Q> struct print_map{
print_map(ostream& out) : tout(out), count(0) {}
void operator() (const pair<T,Q> &x) {
if (count > 0)
tout<<',';
tout<<'('<<x.first<<" => "<<x.second<<')';
++count;
}
ostream& tout;
int count;
};
template<class T,class Q>
ostream & operator << (ostream & tout,map<T,Q> s){
tout<<'{';
for_each(s.begin(),s.end(),print_map<T,Q>(tout));
return(tout<<'}');
}
template<class T>
string to_string(T s){
stringstream tin;
tin<<s;
string res;
getline(tin,res);
return(res);
}
template<class T>
vector<T> to_vector(T *s,int n){
vector<T> result;
for (int i=0;i<n;i++)
result.push_back(s[i]);
return(result);
}
// *********************************** MY CODE ***************************
const int MAX_N = 100+20;
int n,num[MAX_N];
bool good(int k){
map<int,int> mp;
for (int i=1;i<=n;i++)
mp[num[i]>>k]++;
for (map<int,int> :: iterator i=mp.begin();i!=mp.end();i++)
if (i->second*2 > n)
return(false);
return(true);
}
#undef int
int main(){
#define int long long
ios_base::sync_with_stdio(false) ;
cin>>n;
for (int i=1;i<=n;i++)
cin>>num[i];
int biggest = 40;
while (!good(biggest) && biggest >= 0)
biggest--;
cout<<biggest<<endl;
}
Java rep HackerRank Solution
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Solution {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
public static boolean isKMan(int[] a, int n) {
int ct = 1, max = 1;
for (int i = 1; i < n; i++) {
if (a[i] != a[i - 1]) {
ct = 1;
} else {
ct++;
max = Math.max(max, ct);
}
}
return (max <= n / 2);
}
static void solve() {
int n = ni();
int[] array = na(n);
int[] shiftedArray = new int[array.length];
// Arrays.sort(array);
for (int i = 31; i >= 0; i--) {
for (int j = 0; j < n; j++)
shiftedArray[j] = array[j] >>> i;
Arrays.sort(shiftedArray);
// System.out.println(Arrays.toString(shiftedArray));
if (isKMan(shiftedArray, n)) {
out.println(i);
return;
}
}
out.println("-1");
}
public static void main(String[] args) throws Exception {
long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(
INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
long G = System.currentTimeMillis();
tr(G - S + "ms");
}
private static boolean eof() {
if (lenbuf == -1)
return true;
int lptr = ptrbuf;
while (lptr < lenbuf)
if (!isSpaceChar(inbuf[lptr++]))
return false;
try {
is.mark(1000);
while (true) {
int b = is.read();
if (b == -1) {
is.reset();
return true;
} else if (!isSpaceChar(b)) {
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private static int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private static double nd() {
return Double.parseDouble(ns());
}
private static char nc() {
return (char) skip();
}
private static String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b !=
// ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private static int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private static long[] nla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private static int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) {
if (INPUT.length() != 0)
System.out.println(Arrays.deepToString(o));
}
}
Python 3 rep HackerRank Solution
from collections import defaultdict
def topbits(value, k):
return value & ~((1<<k) - 1)
def manipulative_exists( numlist, k ):
tbcount = defaultdict( int )
for num in numlist:
num_tb = topbits( num, k )
tbcount[ num_tb ] += 1
biggest = max( tbcount.values() )
return ( biggest * 2 ) <= len(numlist)
def highest_k( numlist ):
biggest_num = max( numlist )
return biggest_num.bit_length() + 1
def my_main():
listlen_split = input().split()
listlen = int( listlen_split[0] )
numlist_split = input().split()
numlist = [int(x) for x in numlist_split]
maxk = highest_k( numlist )
while maxk > 0 and not manipulative_exists( numlist, maxk ):
maxk = maxk - 1
print( maxk )
my_main()
Python 2 rep HackerRank Solution
# Enter your code here. Read input from STDIN. Print output to STDOUT
from math import log,ceil
def get_input():
temp=raw_input()
return map(int,temp.split())
def get_halfL(L):
mx = max(L)
maxk = int(log(mx,2))
tmpk=maxk+1 # will be shortly removed
grptarget=int(len(L)/2)
while len(L)>grptarget:
tmpk-=1
l=[[],[]]
for elem in L :
l[(elem&(2**tmpk))>0].append(elem)
L=l[ len(l[0]) < len(l[1]) ]
return tmpk
def main():
N = get_input()[0]
L=get_input()
# for aye in range(N):
# L.append(get_input())
k=get_halfL(L[0:N])
print k
if __name__ == '__main__' :
main()
C rep HackerRank Solution
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
#include <stdio.h>
long long a[1000],i,j,k,l,m,n;
int main()
{
scanf("%lld",&n);
for(i=0;i<n;i++) scanf("%lld",&a[i]);
m = n/2;
k=31;
while(n>m)
{
if(k==-1) break;
j=0;
for(i=0;i<n;i++) if(a[i]&(1<<k)) j++;
//printf("%lld %lld %lld %lld\n", j,n, k,1<<k);
if(j<=m && n-j<=m) break;
if(j>n-j)
{
i=0;
for(l=0;l<n;l++) if(a[l]&(1<<k)) a[i++]=a[l];
n=j;
}
else
{
i=0;
for(l=0;l<n;l++) if(!(a[l]&(1<<k))) a[i++]=a[l];
n=n-j;
}
k--;
}
printf("%lld\n",k);
return 0;
}
Warmup
Implementation
Strings
Sorting
Search
Graph Theory
Greedy
Dynamic Programming
Constructive Algorithms
Bit Manipulation
Recursion
Game Theory
NP Complete
Debugging
Leave a comment below