Given an integer array of nums, remove the triplet from last.
The relative order of elements should be kept the same.
Example 1
input : nums = [2,4,2,2,7,5,6,7,8,6,6,2,6,7,6]
output : nums = [2,4,5,6,8,6]
Example 2 input : nums = [2,2,3,2,3,2]
output : nums = [2,3,3]
I have this in java
int[] nums = {2,4,2,2,7,5,6,7,8,6,6,2,6,7,6};
int[] ans = new int[6];
int count=1;
for(int i=0;i<nums.length;i++){
for(int j=0;j<nums.length;j++){
if(arr[i] == arr[j]){
if(count < 3){
count++;
ans[i] = nums[i];
}
}
}
}
I couldn't let this one go, so I did code up an example in c#. This is one approach. There are probably many ways to do this better:
private static int[] RemoveLastTriplet(int[] input)
{
var toRemove = new bool[input.Length];
var counts = new Dictionary<int, int>();
//Count how many times each input value is found.
foreach(var value in input)
{
int count;
if (counts.TryGetValue(value, out count))
{
counts[value] = count + 1;
}
else
{
counts[value] = 1;
}
}
foreach(var kvp in counts)
{
//Determine how many triplets we have for this value
var tripletCount = kvp.Value / 3;
//Keep track of where we're starting
var currentIndex = input.Length - 1;
//Remove each triplet
for(var tripletIndex = 0; tripletIndex < tripletCount; tripletIndex++)
{
//counts the number of elements in this triplet
var thisTripletCount = 0;
//Mark each member of the triplet for deletion.
for(var inputIndex = currentIndex; thisTripletCount < 3; inputIndex--)
{
if (input[inputIndex] == kvp.Key)
{
//Mark this index for removal
toRemove[inputIndex] = true;
thisTripletCount++;
}
//Keep track of where we are in the overall input array
currentIndex--;
}
}
}
//We could be more clever here and keep track of how many
// items we'll have in the output list and just create an array.
var output = new List<int>();
for(int index = 0; index < input.Length; index++)
{
if (!toRemove[index])
{
output.Add(input[index]);
}
}
return output.ToArray();
}
This is my n^2 solution for this problem. I hope it will help you. Just find the count of element first and then find the total number of elements to be removed. Let say it is 't' after that, just replace the t number of elements from the end with -1.
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
int n;
cout << "Enter the length of array : ";
cin >> n;
int arr[n];
cout << "Enter items : ";
for (int i = 0; i < n; ++i)
cin >> arr[i];
// set for fast lookups
unordered_set<int> uset;
for (int i = n - 1; i > -1; --i) {
int e = arr[i];
if (uset.find(e) != uset.end())
continue;
// count the element frequiency
int c = 0;
for (int j = 0; j < n; ++j) {
if (arr[j] == e)
c++;
}
// number of elements would we remove from end
c = c - c % 3;
for (int j = n - 1; j > -1; --j) {
if (c == 0)
break;
if (arr[j] == e) {
arr[j] = -1; // put -1 at removed element location
c--;
}
}
}
// now just print only elemt those value is not equals to zero
for (int i = 0; i < n; ++i) {
if (arr[i] != (-1))
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
arr = input().split()[::-1]
# print(arr)
i = 0
def count_same(num, ind):
count = 0
indexes = []
for index in range(ind, len(arr)):
if arr[index] == num:
count += 1
indexes.append(index)
if count == 3:
break
if count == 3:
for index in indexes[::-1]:
arr.pop(index)
return True
return False
while i < len(arr):
if not count_same(arr[i], i):
i += 1
# print(arr)
print(list(map(int, arr[::-1])))
#include<bits/stdc++.h>
using namespace std;
int main(){
unordered_map<int, int> mp;
vector<int> nums = {2,2,3,2,3,2};
for(auto it:nums){
mp[it]++;
}
for (int i = 0; i < nums.size();i++){
if(mp[nums[i]]%3==0){
continue;
}
else{
cout << nums[i] << " ";
mp[nums[i]] -= mp[nums[i]] / 3;
}
}
}
These python code is working you can use the below exapmles
Example 1:
Input: nums = [2,4,2,2,7,5,6,7,8,6,6,2,6,7,6]
Output: nums = [2,4,5,6,8,6]
Example 2:
Input: nums[2,2,3,2,3,2]
Output: nums[2,3,3]
from collections import defaultdict
nums = list(map(int, input("Enter the elements of the array separated by commas: ").split(',')))
mp = defaultdict(int)
for i in nums:
mp[i] += 1
result = []
for i in nums:
if mp[i] % 3 != 0:
result.append(i)
mp[i] -= mp[i] // 3
print(result)
Related
I want only one loop to archive this output
input={1,2,3,4,5,6,7,8,9} output={1,3,5,7,9,8,6,4,2}
public static void printOddEven(int[] arr) {
int newArray[] = new int[10];
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0) {
newArray[i] = arr[i];
System.out.print(newArray[i] + " ");
}
}
for (int i = arr.length - 1; i > 0; i--) {
if (arr[i] % 2 == 0) {
newArray[i] = arr[i];
System.out.print(newArray[i] + " ");
}
}
}
If you want to use an array:
int [] result = new int[arr.length];
int counterFront = 0;
int counterBack = arr.length - 1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0) {
result[counterFront++] = arr[i];
}
if (arr[i] % 2 == 0) {
result[counterBack--] = arr[i];
}
}
return result;
EDIT: Thanks to a comment, found out it had a ArrayIndexOutOfBounds.
int newArray[] = new int[9];
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0)
newArray[i/2] = arr[i];
else
newArray[8-(i/2)] = arr[i];
}
System.out.println (java.util.Arrays.toString (newArray));
Just use a descendant index from the right
Why do you use Arrays at all? Is it homework? Note that you get an off-by-one-error, because your newArray is too large, when using int[10] for 9 elements, a typical problem with Arrays.
I reckon this is more of a maths problem than a programming problem. It's about knowing there is a simple arithmetic relationship between an incrementing index and a decrementing index.
int[] arr = {1,2,3,4,5,6,7,8,9};
public static void printOddEven(int[] arr) {
int[] odds = new int[5]; // arr.length == 9
int[] even = new int[4];
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
// This is where the magic happens
// It is filling the array from the back
even[even.length - (i / 2) - 1] = arr[i];
} else {
odds[(i / 2)] = arr[i];
}
}
System.out.println(java.util.Arrays.toString(odds));
System.out.println(java.util.Arrays.toString(even));
}
EDIT:
Just for #CoderinoJavarino, here is a version where the output is a single array. The core logic and maths is identical, so take your pick which is easier to understand.
The use of Arrays.toString() is not there as part of the algorithm solution. It is there simply so that you can see the output. I could equally send the output to a file, or to a web socket.
The output is not the printing, the output is the array or arrays. It could equally have been a List, or a special class just for sorting odd/even numbers. Who cares?
In industrial programming (ie, non-academic) this is how code gets divided up: for ease of understanding, not cleverness. And in the business world there is no concept of "cheating": Nobody worries about the internals of, say, a JSP, rendering your array to a browser.
int[] arr = {1,2,3,4,5,6,7,8,9};
public static int[] SORTOddEven(int[] arr) {
int[] output = new int[arr.length]; // arr.length == 9
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
// This is where the magic happens
// It is filling the array from the back
output[output.length - (i / 2) - 1] = arr[i];
} else {
output[(i / 2)] = arr[i];
}
}
return output;
}
System.out.println(java.util.Arrays.toString(SORTOddEven(arr)));
public static void printOddEven(int[] arr) {
int newArray[] = new int[9];
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0)
newArray[i/2] = arr[i];
else
newArray[arr.length - i/2 - 1] = arr[i];
}
System.out.println(java.util.Arrays.toString(newArray));
}
Live on Ideone.
This only works for 123456789 to print 135798642:
public class Sample {
public static void main(String[] args) throws Exception {
int j=0;
int p=2;
int newArray[]= {1,2,3,4,5,6,7,8,9};
for(int i=0;i<=newArray.length-1;i++)
{
if(i<=4)
{
System.out.print(newArray[i]+j);
j++;
}
else
{
System.err.print(newArray[i]+p);
p=p-3;
}
}
}
}
I have been trying to solve the below task:
You are given N counters, initially set to 0, and you have two possible operations on them:
increase(X) − counter X is increased by 1,
max_counter − all counters are set to the maximum value of any counter.
A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:
if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
if A[K] = N + 1 then operation K is max_counter.
For example, given integer N = 5 and array A such that:
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
the values of the counters after each consecutive operation will be:
(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)
The goal is to calculate the value of every counter after all operations.
struct Results {
int * C;
int L;
};
Write a function:
struct Results solution(int N, int A[], int M);
that, given an integer N and a non-empty zero-indexed array A consisting of M integers, returns a sequence of integers representing the values of the counters.
The sequence should be returned as:
a structure Results (in C), or
a vector of integers (in C++), or
a record Results (in Pascal), or
an array of integers (in any other programming language).
For example, given:
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
the function should return [3, 2, 2, 4, 2], as explained above.
Assume that:
N and M are integers within the range [1..100,000];
each element of array A is an integer within the range [1..N + 1].
Complexity:
expected worst-case time complexity is O(N+M);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
Here is my solution:
import java.util.Arrays;
class Solution {
public int[] solution(int N, int[] A) {
final int condition = N + 1;
int currentMax = 0;
int countersArray[] = new int[N];
for (int iii = 0; iii < A.length; iii++) {
int currentValue = A[iii];
if (currentValue == condition) {
Arrays.fill(countersArray, currentMax);
} else {
int position = currentValue - 1;
int localValue = countersArray[position] + 1;
countersArray[position] = localValue;
if (localValue > currentMax) {
currentMax = localValue;
}
}
}
return countersArray;
}
}
Here is the code valuation:
https://codility.com/demo/results/demo6AKE5C-EJQ/
Can you give me a hint what is wrong with this solution?
The problem comes with this piece of code:
for (int iii = 0; iii < A.length; iii++) {
...
if (currentValue == condition) {
Arrays.fill(countersArray, currentMax);
}
...
}
Imagine that every element of the array A was initialized with the value N+1. Since the function call Arrays.fill(countersArray, currentMax) has a time complexity of O(N) then overall your algorithm will have a time complexity O(M * N). A way to fix this, I think, instead of explicitly updating the whole array A when the max_counter operation is called you may keep the value of last update as a variable. When first operation (incrementation) is called you just see if the value you try to increment is larger than the last_update. If it is you just update the value with 1 otherwise you initialize it to last_update + 1. When the second operation is called you just update last_update to current_max. And finally, when you are finished and try to return the final values you again compare each value to last_update. If it is greater you just keep the value otherwise you return last_update
class Solution {
public int[] solution(int N, int[] A) {
final int condition = N + 1;
int currentMax = 0;
int lastUpdate = 0;
int countersArray[] = new int[N];
for (int iii = 0; iii < A.length; iii++) {
int currentValue = A[iii];
if (currentValue == condition) {
lastUpdate = currentMax
} else {
int position = currentValue - 1;
if (countersArray[position] < lastUpdate)
countersArray[position] = lastUpdate + 1;
else
countersArray[position]++;
if (countersArray[position] > currentMax) {
currentMax = countersArray[position];
}
}
}
for (int iii = 0; iii < N; iii++) {
if (countersArray[iii] < lastUpdate)
countersArray[iii] = lastUpdate;
}
return countersArray;
}
}
The problem is that when you get lots of max_counter operations you get lots of calls to Arrays.fill which makes your solution slow.
You should keep a currentMax and a currentMin:
When you get a max_counter you just set currentMin = currentMax.
If you get another value, let's call it i:
If the value at position i - 1 is smaller or equal to currentMin you set it to currentMin + 1.
Otherwise you increment it.
At the end just go through the counters array again and set everything less than currentMin to currentMin.
Another solution that I have developed and might be worth considering: http://codility.com/demo/results/demoM658NU-DYR/
This is the 100% solution of this question.
// you can also use imports, for example:
// import java.math.*;
class Solution {
public int[] solution(int N, int[] A) {
int counter[] = new int[N];
int n = A.length;
int max=-1,current_min=0;
for(int i=0;i<n;i++){
if(A[i]>=1 && A[i]<= N){
if(counter[A[i] - 1] < current_min) counter[A[i] - 1] = current_min;
counter[A[i] - 1] = counter[A[i] - 1] + 1;
if(counter[A[i] - 1] > max) max = counter[A[i] - 1];
}
else if(A[i] == N+1){
current_min = max;
}
}
for(int i=0;i<N;i++){
if(counter[i] < current_min) counter[i] = current_min;
}
return counter;
}
}
I'm adding another Java 100 solution with some test cases it they're helpful.
// https://codility.com/demo/results/demoD8J6M5-K3T/ 77
// https://codility.com/demo/results/demoSEJHZS-ZPR/ 100
public class MaxCounters {
// Some testcases
// (1,[1,2,3]) = [1]
// (1,[1]) = [1]
// (1,[5]) = [0]
// (1,[1,1,1,2,3]) = 3
// (2,[1,1,1,2,3,1]) = [4,3]
// (5, [3, 4, 4, 5, 1, 4, 4]) = (1, 0, 1, 4, 1)
public int[] solution(int N, int[] A) {
int length = A.length, maxOfCounter = 0, lastUpdate = 0;
int applyMax = N + 1;
int result[] = new int[N];
for (int i = 0; i < length; ++i ) {
if(A[i] == applyMax){
lastUpdate = maxOfCounter;
} else if (A[i] <= N) {
int position = A[i]-1;
result[position] = result[position] > lastUpdate
? result[position] + 1 : lastUpdate + 1;
// updating the max for future use
if(maxOfCounter <= result[position]) {
maxOfCounter = result[position];
}
}
}
// updating all the values that are less than the lastUpdate to the max value
for (int i = 0; i < N; ++i) {
if(result[i] < lastUpdate) {
result[i] = lastUpdate;
}
}
return result;
}
}
My java solution with a detailed explanation 100% Correctness, 100% Performance :
Time Complexity O(N+M)
public static int[] solution(int N, int[] A) {
int[] counters = new int[N];
//The Max value between all counters at a given time
int max = 0;
//The base Max that all counter should have after the "max counter" operation happens
int baseMax = 0;
for (int i = 0; i < A.length; i++) {
//max counter Operation ==> updating the baseMax
if (A[i] > N) {
// Set The Base Max that all counters should have
baseMax = max;
}
//Verify if the value is bigger than the last baseMax because at any time a "max counter" operation can happen and the counter should have the max value
if (A[i] <= N && counters[A[i] - 1] < baseMax) {
counters[A[i] - 1] = baseMax;
}
//increase(X) Operation => increase the counter value
if (A[i] <= N) {
counters[A[i] - 1] = counters[A[i] - 1] + 1;
//Update the max
max = Math.max(counters[A[i] - 1], max);
}
}
//Set The remaining values to the baseMax as not all counters are guaranteed to be affected by an increase(X) operation in "counters[A[i] - 1] = baseMax;"
for (int j = 0; j < N; j++) {
if (counters[j] < baseMax)
counters[j] = baseMax;
}
return counters;
}
Here is my C++ solution which got 100 on codility. The concept is same as explained above.
int maxx=0;
int lastvalue=0;
void set(vector<int>& A, int N,int X)
{
for ( int i=0;i<N;i++)
if(A[i]<lastvalue)
A[i]=lastvalue;
}
vector<int> solution(int N, vector<int> &A) {
// write your code in C++11
vector<int> B(N,0);
for(unsigned int i=0;i<A.size();i++)
{
if(A[i]==N+1)
lastvalue=maxx;
else
{ if(B[A[i]-1]<lastvalue)
B[A[i]-1]=lastvalue+1;
else
B[A[i]-1]++;
if(B[A[i]-1]>maxx)
maxx=B[A[i]-1];
}
}
set(B,N,maxx);
return B;
}
vector<int> solution(int N, vector<int> &A)
{
std::vector<int> counters(N);
auto max = 0;
auto current = 0;
for (auto& counter : A)
{
if (counter >= 1 && counter <= N)
{
if (counters[counter-1] < max)
counters[counter - 1] = max;
counters[counter - 1] += 1;
if (counters[counter - 1] > current)
current = counters[counter - 1];
}
else if (counter > N)
max = current;
}
for (auto&& counter : counters)
if (counter < max)
counter = max;
return counters;
}
Arrays.fill() invocation inside array interation makes the program O(N^2)
Here is a possible solution which has O(M+N) runtime.
The idea is -
For the second operation, keep track of max value that is achieved through increment, this is our base value till the current iteration, no values can't be less than this.
For the first operation, resetting the value to base value if needed before the increment.
public static int[] solution(int N, int[] A) {
int counters[] = new int[N];
int base = 0;
int cMax = 0;
for (int a : A) {
if (a > counters.length) {
base = cMax;
} else {
if (counters[a - 1] < base) {
counters[a - 1] = base;
}
counters[a - 1]++;
cMax = Math.max(cMax, counters[a - 1]);
}
}
for (int i = 0; i < counters.length; i++) {
if (counters[i] < base) {
counters[i] = base;
}
}
return counters;
}
vector<int> solution(int N, vector<int> &A)
{
std::vector<int> counter(N, 0);
int max = 0;
int floor = 0;
for(std::vector<int>::iterator i = A.begin();i != A.end(); i++)
{
int index = *i-1;
if(*i<=N && *i >= 1)
{
if(counter[index] < floor)
counter[index] = floor;
counter[index] += 1;
max = std::max(counter[index], max);
}
else
{
floor = std::max(max, floor);
}
}
for(std::vector<int>::iterator i = counter.begin();i != counter.end(); i++)
{
if(*i < floor)
*i = floor;
}
return counter;
}
Hera is my AC Java solution. The idea is the same as #Inwvr explained:
public int[] solution(int N, int[] A) {
int[] count = new int[N];
int max = 0;
int lastUpdate = 0;
for(int i = 0; i < A.length; i++){
if(A[i] <= N){
if(count[A[i]-1] < lastUpdate){
count[A[i]-1] = lastUpdate+1;
}
else{
count[A[i]-1]++;
}
max = Math.max(max, count[A[i]-1]);
}
else{
lastUpdate = max;
}
}
for(int i = 0; i < N; i++){
if(count[i] < lastUpdate)
count[i] = lastUpdate;
}
return count;
}
I just got 100 in PHP with some help from the above
function solution($N, $A) {
$B = array(0);
$max = 0;
foreach($A as $key => $a) {
$a -= 1;
if($a == $N) {
$max = max($B);
} else {
if(!isset($B[$a])) {
$B[$a] = 0;
}
if($B[$a] < $max) {
$B[$a] = $max + 1;
} else {
$B[$a] ++;
}
}
}
for($i=0; $i<$N; $i++) {
if(!isset($B[$i]) || $B[$i] < $max) {
$B[$i] = $max;
}
}
return $B;
}
This is another C++ solution to the problem.
The rationale is always the same.
Avoid to set to max counter all the counter upon instruction two, as this would bring the complexity to O(N*M).
Wait until we get another operation code on a single counter.
At this point the algorithm remembers whether it had met a max_counter and set the counter value consequently.
Here the code:
vector<int> MaxCounters(int N, vector<int> &A)
{
vector<int> n(N, 0);
int globalMax = 0;
int localMax = 0;
for( vector<int>::const_iterator it = A.begin(); it != A.end(); ++it)
{
if ( *it >= 1 && *it <= N)
{
// this is an increase op.
int value = *it - 1;
n[value] = std::max(n[value], localMax ) + 1;
globalMax = std::max(n[value], globalMax);
}
else
{
// set max counter op.
localMax = globalMax;
}
}
for( vector<int>::iterator it = n.begin(); it != n.end(); ++it)
*it = std::max( *it, localMax );
return n;
}
100%, O(m+n)
public int[] solution(int N, int[] A) {
int[] counters = new int[N];
int maxAIs = 0;
int minAShouldBe = 0;
for(int x : A) {
if(x >= 1 && x <= N) {
if(counters[x-1] < minAShouldBe) {
counters[x-1] = minAShouldBe;
}
counters[x-1]++;
if(counters[x-1] > maxAIs) {
maxAIs = counters[x-1];
}
} else if(x == N+1) {
minAShouldBe = maxAIs;
}
}
for(int i = 0; i < N; i++) {
if(counters[i] < minAShouldBe) {
counters[i] = minAShouldBe;
}
}
return counters;
}
here is my code, but its 88% cause it takes 3.80 sec for 10000 elements instead of 2.20
class Solution {
boolean maxCalled;
public int[] solution(int N, int[] A) {
int max =0;
int [] counters = new int [N];
int temp=0;
int currentVal = 0;
for(int i=0;i<A.length;i++){
currentVal = A[i];
if(currentVal <=N){
temp = increas(counters,currentVal);
if(temp > max){
max = temp;
}
}else{
if(!maxCalled)
maxCounter(counters,max);
}
}
return counters;
}
int increas (int [] A, int x){
maxCalled = false;
return ++A[x-1];
//return t;
}
void maxCounter (int [] A, int x){
maxCalled = true;
for (int i = 0; i < A.length; i++) {
A[i] = x;
}
}
}
Following my solution in JAVA (100/100).
public boolean isToSum(int value, int N) {
return value >= 1 && value <= N;
}
public int[] solution(int N, int[] A) {
int[] res = new int[N];
int max =0;
int minValue = 0;
for (int i=0; i < A.length; i++){
int value = A[i];
int pos = value -1;
if ( isToSum(value, N)) {
if( res[pos] < minValue) {
res[pos] = minValue;
}
res[pos] += 1;
if (max < res[pos]) {
max = res[pos];
}
} else {
minValue = max;
}
}
for (int i=0; i < res.length; i++){
if ( res[i] < minValue ){
res[i] = minValue;
}
}
return res;
}
my solution is :
public class Solution {
public int[] solution(int N, int[] A) {
int[] counters = new int[N];
int[] countersLastMaxIndexes = new int[N];
int maxValue = 0;
int fixedMaxValue = 0;
int maxIndex = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] <= N) {
if (countersLastMaxIndexes[A[i] - 1] != maxIndex) {
counters[A[i] - 1] = fixedMaxValue;
countersLastMaxIndexes[A[i] - 1] = maxIndex;
}
counters[A[i] - 1]++;
if (counters[A[i] - 1] > maxValue) {
maxValue = counters[A[i] - 1];
}
} else {
maxIndex = i;
fixedMaxValue = maxValue;
}
}
for (int i = 0; i < countersLastMaxIndexes.length; i++) {
if (countersLastMaxIndexes[i] != maxIndex) {
counters[i] = fixedMaxValue;
countersLastMaxIndexes[i] = maxIndex;
}
}
return counters;
}
}
In my Java solution I updated values in solution[] only when needed. And finally updated solution[] with a right values.
public int[] solution(int N, int[] A) {
int[] solution = new int[N];
int maxCounter = 0;
int maxCountersSum = 0;
for(int a: A) {
if(a >= 1 && a <= N) {
if(solution[a - 1] < maxCountersSum)
solution[a - 1] = maxCountersSum;
solution[a - 1]++;
if(solution[a - 1] > maxCounter)
maxCounter = solution[a - 1];
}
if(a == N + 1) {
maxCountersSum = maxCounter;
}
}
for(int i = 0; i < N; i++) {
if(solution[i] < maxCountersSum)
solution[i] = maxCountersSum;
}
return solution;
}
Here's my python solution:
def solution(N, A):
# write your code in Python 3.6
RESP = [0] * N
MAX_OPERATION = N + 1
current_max = 0
current_min = 0
for operation in A:
if operation != MAX_OPERATION:
if RESP[operation-1] <= current_min:
RESP[operation-1] = current_min + 1
else:
RESP[operation-1] += 1
if RESP[operation-1] > current_max:
current_max = RESP[operation-1]
else:
if current_min == current_max:
current_min += 1
else:
current_min = current_max
for i, val in enumerate(RESP):
if val < current_min:
RESP[i] = current_min
return RESP
def sample_method(A,N=5):
initial_array = [0,0,0,0,0]
for i in A:
if(i>=1):
if(i<=N):
initial_array[i-1]+=1
else:
for a in range(len(initial_array)):
initial_array[a]+=1
print i
print initial_array
Here's my solution using python 3.6. The result is 100% correctness but 40% performance (most of them were because of timeout). Still cannot figure out how to optimize this code but hopefully someone can find it useful.
def solution(N, A):
count = [0]*(N+1)
for i in range(0,len(A)):
if A[i] >=1 and A[i] <= N:
count[A[i]] += 1
elif A[i] == (N+1):
count = [max(count)] * len(count)
count.pop(0)
return count
Typescript:
function counters(numCounters: number, operations: number[]) {
const counters = Array(numCounters)
let max = 0
let currentMin = 0
for (const operation of operations) {
if (operation === numCounters + 1) {
currentMin = max
} else {
if (!counters[operation - 1] || counters[operation - 1] < currentMin) {
counters[operation - 1] = currentMin
}
counters[operation - 1] = counters[operation - 1] + 1
if (counters[operation - 1] > max) {
max += 1
}
}
}
for (let i = 0; i < numCounters; i++) {
if (!counters[i] || counters[i] < currentMin) {
counters[i] = currentMin
}
}
return counters
}
console.log(solution=${counters(5, [3, 4, 4, 6, 1, 4, 4])})
100 points JavaScript solution, includes performance improvement to ignore repeated max_counter iterations:
function solution(N, A) {
let max = 0;
let counters = Array(N).fill(max);
let maxCounter = 0;
for (let op of A) {
if (op <= N && op >= 1) {
maxCounter = 0;
if (++counters[op - 1] > max) {
max = counters[op - 1];
}
} else if(op === N + 1 && maxCounter === 0) {
maxCounter = 1;
for (let i = 0; i < counters.length; i++) {
counters[i] = max;
}
}
}
return counters;
}
solution in JAVA (100/100)
class Solution {
public int[] solution(int N, int[] A) {
// write your code in Java SE 8
int[] result = new int[N];
int base = 0;
int max = 0;
int needToChange=A.length;;
for (int k = 0; k < A.length; k++) {
int X = A[k];
if (X >= 1 && X <= N) {
if (result[X - 1] < base) {
result[X - 1] = base;
}
result[X - 1]++;
if (max < result[X - 1]) {
max = result[X - 1];
}
}
if (X == N + 1) {
base = max;
needToChange= X-1;
}
}
for (int i = 0; i < needToChange; i++) {
if (result[i] < base) {
result[i] = base;
}
}
return result;
}
}
My Java solution. It gives 100% but is very long (in comparison). I have used HashMap for storing counters.
Detected time complexity: O(N + M)
import java.util.*;
class Solution {
final private Map<Integer, Integer> counters = new HashMap<>();
private int maxCounterValue = 0;
private int maxCounterValueRealized = 0;
public int[] solution(int N, int[] A) {
if (N < 1) return new int[0];
for (int a : A) {
if (a <= N) {
Integer current = counters.putIfAbsent(a, maxCounterValueRealized + 1);
if (current == null) {
updateMaxCounterValue(maxCounterValueRealized + 1);
} else {
++current;
counters.replace(a, current);
updateMaxCounterValue(current);
}
} else {
maxCounterValueRealized = maxCounterValue;
counters.clear();
}
}
return getCountersArray(N);
}
private void updateMaxCounterValue(int currentCounterValue) {
if (currentCounterValue > maxCounterValue)
maxCounterValue = currentCounterValue;
}
private int[] getCountersArray(int N) {
int[] countersArray = new int[N];
for (int j = 0; j < N; j++) {
Integer current = counters.get(j + 1);
if (current == null) {
countersArray[j] = maxCounterValueRealized;
} else {
countersArray[j] = current;
}
}
return countersArray;
}
}
Here is solution in python with 100 %
Codility Max counter 100%
def solution(N, A):
"""
Solution at 100% - https://app.codility.com/demo/results/trainingUQ95SB-4GA/
Idea is first take the counter array of given size N
take item from main A one by one + 1 and put in counter array , use item as index
keep track of last max operation
at the end replace counter items with max of local or counter item it self
:param N:
:param A:
:return:
"""
global_max = 0
local_max = 0
# counter array
counter = [0] * N
for i, item in enumerate(A):
# take item from original array one by one - 1 - minus due to using item as index
item_as_counter_index = item - 1
# print(item_as_counter_index)
# print(counter)
# print(local_max)
# current element less or equal value in array and greater than 1
# if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
if N >= item >= 1:
# max of local_max counter at item_as_counter_index
# increase counter array value and put in counter array
counter[item_as_counter_index] = max(local_max, counter[item_as_counter_index]) + 1
# track the status of global_max counter so far
# this is operation K
global_max = max(global_max, counter[item_as_counter_index])
# if A[K] = N + 1 then operation K is max counter.
elif item == N + 1:
# now operation k is as local max
# here we need to replace all items in array with this global max
# we can do using for loop for array length but that will cost bigo n2 complexity
# example - for i, item in A: counter[i] = global_max
local_max = global_max
# print("global_max each step")
# print(global_max)
# print("local max so far....")
# print(local_max)
# print("counter - ")
# print(counter)
# now counter array - replace all elements which are less than the local max found so far
# all counters are set to the maximum value of any counter
for i, item in enumerate(counter):
counter[i] = max(item, local_max)
return counter
result = solution(1, [3, 4, 4, 6, 1, 4, 4])
print("Sol " + str(result))
enter link description here
Got 100% result with O ( N + M )
class Solution {
public int[] solution(int N, int[] A) {
// write your code in Java SE 8
int max = 0;
int[] counter = new int[N];
int upgrade = 0;
for ( int i = 0; i < A.length; i++ )
{
if ( A[i] <= N )
{
if ( upgrade > 0 && upgrade > counter[A[i] - 1 ] )
{
counter[A[i] - 1] = upgrade;
}
counter[A[i] - 1 ]++;
if ( counter[A[i] - 1 ] > max )
{
max = counter[A[i] - 1 ];
}
}
else
{
upgrade = max;
}
}
for ( int i = 0; i < N; i++ )
{
if ( counter[i] < upgrade)
{
counter[i] = upgrade;
}
}
return counter;
}
}
Java 100%/100%, no imports
public int[] solution(int N, int[] A) {
int[] counters = new int[N];
int currentMax = 0;
int sumOfMaxCounters = 0;
boolean justDoneMaxCounter = false;
for (int i = 0; i < A.length ; i++) {
if (A[i] <= N) {
justDoneMaxCounter = false;
counters[A[i]-1]++;
currentMax = currentMax < counters[A[i]-1] ? counters[A[i]-1] : currentMax;
}else if (!justDoneMaxCounter){
sumOfMaxCounters += currentMax;
currentMax = 0;
counters = new int[N];
justDoneMaxCounter = true;
}
}
for (int j = 0; j < counters.length; j++) {
counters[j] = counters[j] + sumOfMaxCounters;
}
return counters;
}
python solution: 100% 100%
def solution(N, A):
c = [0] * N
max_element = 0
base = 0
for item in A:
if item >= 1 and N >= item:
c[item-1] = max(c[item-1], base) + 1
max_element = max(c[item - 1], max_element)
elif item == N + 1:
base = max_element
for i in range(N):
c[i] = max (c[i], base)
return c
pass
Using applyMax to record max operations
Time complexity:
O(N + M)
class Solution {
public int[] solution(int N, int[] A) {
// write your code in Java SE 8
int max = 0, applyMax = 0;;
int[] result = new int[N];
for (int i = 0; i < A.length; ++i) {
int a = A[i];
if (a == N + 1) {
applyMax = max;
}
if (1 <= a && a <= N) {
result[A[i] - 1] = Math.max(applyMax, result[A[i] - 1]);
max = Math.max(max, ++result[A[i] - 1]);
}
}
for (int i = 0; i < N; ++i) {
if (result[i] < applyMax) {
result[i] = applyMax;
}
}
return result;
}
}
I how can I find the positions of the three lowest integers in an array?
I've tried to reverse it, but when I add a third number, it all goes to hell :p
Does anybody manage to pull this one off and help me? :)
EDIT: It would be nice to do it without changing or sorting the original array a.
public static int[] lowerThree(int[] a) {
int n = a.length;
if (n < 2) throw
new java.util.NoSuchElementException("a.length(" + n + ") < 2!");
int m = 0; // position for biggest
int nm = 1; // position for second biggest
if (a[1] > a[0]) { m = 1; nm = 0; }
int biggest = a[m]; // biggest value
int secondbiggest = a[nm]; // second biggest
for (int i = 2; i < n; i++) {
if (a[i] > secondbiggest) {
if (a[i] > biggest) {
nm = m;
secondbiggest = biggest;
m = i;
biggest = a[m];
}
else {
nm = i;
secondbiggest = a[nm];
}
}
} // for
return new int[] {m,nm};
}
EDIT: I've tried something here but it still doesn't work. I get wrong output + duplicates...
public static int[] lowerthree(int[] a) {
int n= a.length;
if(n < 3)
throw new IllegalArgumentException("wrong");
int m = 0;
int nm = 1;
int nnm= 2;
int smallest = a[m]; //
int secondsmallest = a[nm]; /
int thirdsmallest= a[nnm];
for(int i= 0; i< lengde; i++) {
if(a[i]< smallest) {
if(smalles< secondsmallest) {
if(secondsmallest< thirdsmallest) {
nnm= nm;
thirdsmallest= secondsmallest;
}
nm= m;
secondsmallest= smallest;
}
m= i;
smallest= a[m];
}
else if(a[i] < secondsmallest) {
if(secondsmallest< thirdsmallest) {
nnm= nm;
thirdsmallest= secondsmallest;
}
nm= i;
secondsmallest= a[nm];
}
else if(a[i]< thirdsmallest) {
nnm= i;
thirdsmallest= a[nnm];
}
}
return new int[] {m, nm, nnm};
}
Getting the top or bottom k is usually done with a partial sort. There are versions that change the original array and those that dont.
If you only want the bottom (exactly) 3 and want to get their positions, not the values, your solution might be the best fit. This is how I would change it to support the bottom three. (I have not tried to compile and run, there may be little mistakes but the genereal idea should fit)
public static int[] lowerThree(int[] a) {
if (a.length < 3) throw
new java.util.NoSuchElementException("...");
int indexSmallest = 0;
int index2ndSmallest = 0;
int index3rdSmallest = 0;
int smallest = Integer.MAX_VALUE;
int sndSmallest = Integer.MAX_VALUE;
int trdSmallest = Integer.MAX_VALUE;
for (size_t i = 0; i < a.length; ++i) {
if (a[i] < trdSmallest) {
if (a[i] < sndSmallest) {
if (a[i] < smallest) {
trdSmallest = sndSmallest;
index3rdSmallest = index2ndSmallest;
sndSmallest = smallest;
index2ndSmallest = indexSmallest;
smallest = a[i];
indexSmallest = i;
continue;
}
trdSmallest = sndSmallest;
index3rdSmallest = index2ndSmallest;
sndSmallest = a[i];
index2ndSmallest = i;
continue;
}
trdSmallest = a[i];
index3rdSmallest = i;
}
}
return new int[] {indexSmallest, index2ndSmallest, index3rdSmallest};
}
This will have the three lowest numbers, need to add some test cases..but here is the idea
int[] arr = new int[3];
arr[0] = list.get(0);
if(list.get(1) <= arr[0]){
int temp = arr[0];
arr[0] = list.get(1);
arr[1] = temp;
}
else{
arr[1] = list.get(1);
}
if(list.get(2) < arr[1]){
if(list.get(2) < arr[0]){
arr[2] = arr[1];
arr[1] = arr[0];
arr[0] = list.get(2);
}
else{
arr[2] = arr[1];
arr[1] = list.get(2);
}
}else{
arr[2] = list.get(2);
}
for(int integer = 3 ; integer < list.size() ; integer++){
if(list.get(integer) < arr[0]){
int temp = arr[0];
arr[0] = list.get(integer);
arr[2] = arr[1];
arr[1] = temp;
}
else if(list.get(integer) < arr[1]){
int temp = arr[1];
arr[1] = list.get(integer);
arr[2] = temp;
}
else if(list.get(integer) <= arr[2]){
arr[2] = list.get(integer);
}
}
I'd store the lowest elements in a LinkedList, so it is not fixed on the lowest 3 elements. What do you think?
public static int[] lowest(int[] arr, int n) {
LinkedList<Integer> res = new LinkedList();
for(int i = 0; i < arr.length; i++) {
boolean added = false;
//iterate over all elements in the which are of interest (n first)
for(int j = 0; !added && j < n && j < res.size(); j++) {
if(arr[i] < res.get(j)) {
res.add(j, i); //the element is less than the element currently considered
//one of the lowest n, so insert it
added = true; //help me get out of the loop
}
}
//Still room in the list, so let's append it
if(!added && res.size() < n) {
res.add(i);
}
}
//copy first n indices to result array
int[] r = new int[n];
for(int i = 0; i < n && i < res.size(); i++) {
r[i] = res.get(i);
}
return r;
}
In simple words, you need to compare every new element with the maximum of the three you have at hand, and swap them if needed (and if you swap, max of the three has to be recalculated).
I would use 2 arrays of size 3 each:
arrValues = [aV1 aV2 aV3] (reals)
arrPointers = [aP1 aP2 aP3] (integers)
and a 64 bit integer type, call it maxPointer.
I will outline the algorithm logic, since I am not familiar with Java:
Set arrValues = array[0] array[1] array[2] (three first elements of your array)
Set arrPointers = [0 1 2] (or [1 2 3] if your array starts from 1)
Iterate over the remaining elements. In each loop:
Compare the Element scanned in this iteration with arrValues[maxPointer]
If Element <= arrValues[maxPointer],
remove the maxPointer element,
find the new max element and reset the maxPointer
Else
scan next element
End If
Loop
At termination, arrPointers should have the positions of the three smallest elements.
I hope this helps?
There is an easy way to find the positions of three lowest number in an Array
Example :
int[] arr={3,5,1,2,9,7};
int[] position=new int[arr.length];
for(int i=0;i<arr.length;i++)
{
position[i]=i;
}
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]>arr[j]){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
int tem=position[i];
position[i]=position[j];
position[j]=tem;
}
}
}
System.out.println("Lowest numbers in ascending order");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
System.out.println("And their previous positions ");
for(int i=0;i<arr.length;i++)
{
System.out.println(position[i]);
}
Output
you can do it in 3 iterations.
You need two extra memory, one for location and one for value.
First iteration, you will keep the smallest value in one extra memory and its location in the second. As you are iterating, you compare every value in the slot with the value slot you keep in the memory, if the item you are visiting is smaller than what you have in your extra value slot, you replace the value as well as the location.
At the end of your first iteration, you will find the smallest element and its corresponding location.
You do the same for second and third smallest.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I just had a codility problem give me a hard time and I'm still trying to figure out how the space and time complexity constraints could have been met.
The problem is as follows:
A dominant member in the array is one that occupies over half the positions in the array, for example:
{3, 67, 23, 67, 67}
67 is a dominant member because it appears in the array in 3/5 (>50%) positions.
Now, you are expected to provide a method that takes in an array and returns an index of the dominant member if one exists and -1 if there is none.
Easy, right? Well, I could have solved the problem handily if it were not for the following constraints:
Expected time complexity is O(n)
Expected space complexity is O(1)
I can see how you could solve this for O(n) time with O(n) space complexities as well as O(n^2) time with O(1) space complexities, but not one that meets both O(n) time and O(1) space.
I would really appreciate seeing a solution to this problem. Don't worry, the deadline has passed a few hours ago (I only had 30 minutes), so I'm not trying to cheat. Thanks.
Googled "computing dominant member of array", it was the first result. See the algorithm described on page 3.
element x;
int count ← 0;
For(i = 0 to n − 1) {
if(count == 0) { x ← A[i]; count++; }
else if (A[i] == x) count++;
else count−−;
}
Check if x is dominant element by scanning array A
Basically observe that if you find two different elements in the array, you can remove them both without changing the dominant element on the remainder. This code just keeps tossing out pairs of different elements, keeping track of the number of times it has seen the single remaining unpaired element.
Find the median with BFPRT, aka median of medians (O(N) time, O(1) space). Then scan through the array -- if one number dominates, the median will be equal to that number. Walk through the array and count the number of instances of that number. If it's over half the array, it's the dominator. Otherwise, there is no dominator.
Adding a Java 100/100 O(N) time with O(1) space:
https://codility.com/demo/results/demoPNG8BT-KEH/
class Solution {
public int solution(int[] A) {
int indexOfCandidate = -1;
int stackCounter = 0, candidate=-1, value=-1, i =0;
for(int element: A ) {
if (stackCounter == 0) {
value = element;
++stackCounter;
indexOfCandidate = i;
} else {
if (value == element) {
++stackCounter;
} else {
--stackCounter;
}
}
++i;
}
if (stackCounter > 0 ) {
candidate = value;
} else {
return -1;
}
int countRepetitions = 0;
for (int element: A) {
if( element == candidate) {
++countRepetitions;
}
if(countRepetitions > (A.length / 2)) {
return indexOfCandidate;
}
}
return -1;
}
}
If you want to see the Java source code it's here, I added some test cases as comments as the beginning of the file.
Java solution with score 100%
public int solution(int[] array) {
int candidate=0;
int counter = 0;
// Find candidate for leader
for(int i=0; i<array.length; i++){
if(counter == 0) candidate = i;
if(array[i] == array[candidate]){
counter++;
}else {
counter--;
}
}
// Count candidate occurrences in array
counter = 0;
for(int i=0; i<array.length; i++){
if(array[i] == array[candidate]) counter++;
}
// Check that candidate occurs more than array.lenght/2
return counter>array.length/2 ? candidate : -1;
}
In python, we are lucky some smart people have bothered to implement efficient helpers using C and shipped it in the standard library. The collections.Counter is useful here.
>>> data = [3, 67, 23, 67, 67]
>>> from collections import Counter
>>> counter = Counter(data) # counter accepts any sequence/iterable
>>> counter # dict like object, where values are the occurrence
Counter({67: 3, 3: 1, 23: 1})
>>> common = counter.most_common()[0]
>>> common
(67, 3)
>>> common[0] if common[1] > len(data) / 2.0 + 1 else -1
67
>>>
If you prefer a function here is one ...
>>> def dominator(seq):
counter = Counter(seq)
common = counter.most_common()[0]
return common[0] if common[1] > len(seq) / 2.0 + 1 else -1
...
>>> dominator([1, 3, 6, 7, 6, 8, 6])
-1
>>> dominator([1, 3, 6, 7, 6, 8, 6, 6])
6
This question looks hard if a small trick does not come to the mind :). I found this trick in this document of codility : https://codility.com/media/train/6-Leader.pdf.
The linear solution is explained at the bottom of this document.
I implemented the following java program which gave me a score of 100 on the same lines.
public int solution(int[] A) {
Stack<Integer> stack = new Stack<Integer>();
for (int i =0; i < A.length; i++)
{
if (stack.empty())
stack.push(new Integer(A[i]));
else
{
int topElem = stack.peek().intValue();
if (topElem == A[i])
{
stack.push(new Integer(A[i]));
}
else
{
stack.pop();
}
}
}
if (stack.empty())
return -1;
int elem = stack.peek().intValue();
int count = 0;
int index = 0;
for (int i = 0; i < A.length; i++)
{
if (elem == A[i])
{
count++;
index = i;
}
}
if (count > ((double)A.length/2.0))
return index;
else
return -1;
}
Here's my C solution which scores 100%
int solution(int A[], int N) {
int candidate;
int count = 0;
int i;
// 1. Find most likely candidate for the leader
for(i = 0; i < N; i++){
// change candidate when count reaches 0
if(count == 0) candidate = i;
// count occurrences of candidate
if(A[i] == A[candidate]) count++;
else count--;
}
// 2. Verify that candidate occurs more than N/2 times
count = 0;
for(i = 0; i < N; i++) if(A[i] == A[candidate]) count++;
if (count <= N/2) return -1;
return candidate; // return index of leader
}
100%
import java.util.HashMap;
import java.util.Map;
class Solution {
public static int solution(int[] A) {
final int N = A.length;
Map<Integer, Integer> mapOfOccur = new HashMap((N/2)+1);
for(int i=0; i<N; i++){
Integer count = mapOfOccur.get(A[i]);
if(count == null){
count = 1;
mapOfOccur.put(A[i],count);
}else{
mapOfOccur.replace(A[i], count, ++count);
}
if(count > N/2)
return i;
}
return -1;
}
}
Does it have to be a particularly good algorithm? ;-)
static int dominant(final int... set) {
final int[] freqs = new int[Integer.MAX_VALUE];
for (int n : set) {
++freqs[n];
}
int dom_freq = Integer.MIN_VALUE;
int dom_idx = -1;
int dom_n = -1;
for (int i = set.length - 1; i >= 0; --i) {
final int n = set[i];
if (dom_n != n) {
final int freq = freqs[n];
if (freq > dom_freq) {
dom_freq = freq;
dom_n = n;
dom_idx = i;
} else if (freq == dom_freq) {
dom_idx = -1;
}
}
}
return dom_idx;
}
(this was primarily meant to poke fun at the requirements)
Consider this 100/100 solution in Ruby:
# Algorithm, as described in https://codility.com/media/train/6-Leader.pdf:
#
# * Iterate once to find a candidate for dominator.
# * Count number of candidate occurences for the final conclusion.
def solution(ar)
n_occu = 0
candidate = index = nil
ar.each_with_index do |elem, i|
if n_occu < 1
# Here comes a new dominator candidate.
candidate = elem
index = i
n_occu += 1
else
if candidate == elem
n_occu += 1
else
n_occu -= 1
end
end # if n_occu < 1
end
# Method result. -1 if no dominator.
# Count number of occurences to check if candidate is really a dominator.
if n_occu > 0 and ar.count {|_| _ == candidate} > ar.size/2
index
else
-1
end
end
#--------------------------------------- Tests
def test
sets = []
sets << ["4666688", [1, 2, 3, 4], [4, 6, 6, 6, 6, 8, 8]]
sets << ["333311", [0, 1, 2, 3], [3, 3, 3, 3, 1, 1]]
sets << ["313131", [-1], [3, 1, 3, 1, 3, 1]]
sets << ["113333", [2, 3, 4, 5], [1, 1, 3, 3, 3, 3]]
sets.each do |name, one_of_expected, ar|
out = solution(ar)
raise "FAILURE at test #{name.inspect}: #{out.inspect} not in #{expected.inspect}" if not one_of_expected.include? out
end
puts "SUCCESS: All tests passed"
end
Here is an easy to read, 100% score version in Objective-c
if (A.count > 100000)
return -1;
NSInteger occur = 0;
NSNumber *candidate = nil;
for (NSNumber *element in A){
if (!candidate){
candidate = element;
occur = 1;
continue;
}
if ([candidate isEqualToNumber:element]){
occur++;
}else{
if (occur == 1){
candidate = element;
continue;
}else{
occur--;
}
}
}
if (candidate){
occur = 0;
for (NSNumber *element in A){
if ([candidate isEqualToNumber:element])
occur++;
}
if (occur > A.count / 2)
return [A indexOfObject:candidate];
}
return -1;
100% score JavaScript solution. Technically it's O(nlogn) but still passed.
function solution(A) {
if (A.length == 0)
return -1;
var S = A.slice(0).sort(function(a, b) {
return a - b;
});
var domThresh = A.length/2;
var c = S[Math.floor(domThresh)];
var domCount = 0;
for (var i = 0; i < A.length; i++) {
if (A[i] == c)
domCount++;
if (domCount > domThresh)
return i;
}
return -1;
}
This is the solution in VB.NET with 100% performance.
Dim result As Integer = 0
Dim i, ladderVal, LadderCount, size, valCount As Integer
ladderVal = 0
LadderCount = 0
size = A.Length
If size > 0 Then
For i = 1 To size - 1
If LadderCount = 0 Then
LadderCount += 1
ladderVal = A(i)
Else
If A(i) = ladderVal Then
LadderCount += 1
Else
LadderCount -= 1
End If
End If
Next
valCount = 0
For i = 0 To size - 1
If A(i) = ladderVal Then
valCount += 1
End If
Next
If valCount <= size / 2 Then
result = 0
Else
LadderCount = 0
For i = 0 To size - 1
If A(i) = ladderVal Then
valCount -= 1
LadderCount += 1
End If
If LadderCount > (LadderCount + 1) / 2 And (valCount > (size - (i + 1)) / 2) Then
result += 1
End If
Next
End If
End If
Return result
See the correctness and performance of the code
Below solution resolves in complexity O(N).
public int solution(int A[]){
int dominatorValue=-1;
if(A != null && A.length>0){
Hashtable<Integer, Integer> count=new Hashtable<>();
dominatorValue=A[0];
int big=0;
for (int i = 0; i < A.length; i++) {
int value=0;
try{
value=count.get(A[i]);
value++;
}catch(Exception e){
}
count.put(A[i], value);
if(value>big){
big=value;
dominatorValue=A[i];
}
}
}
return dominatorValue;
}
100% in PHP https://codility.com/demo/results/trainingVRQGQ9-NJP/
function solution($A){
if (empty($A)) return -1;
$copy = array_count_values($A); // 3 => 7, value => number of repetition
$max_repetition = max($copy); // at least 1 because the array is not empty
$dominator = array_search($max_repetition, $copy);
if ($max_repetition > count($A) / 2) return array_search($dominator, $A); else return -1;
}
i test my code its work fine in arrays lengths between 2 to 9
public static int sol (int []a)
{
int count = 0 ;
int candidateIndex = -1;
for (int i = 0; i <a.length ; i++)
{
int nextIndex = 0;
int nextOfNextIndex = 0;
if(i<a.length-2)
{
nextIndex = i+1;
nextOfNextIndex = i+2;
}
if(count==0)
{
candidateIndex = i;
}
if(a[candidateIndex]== a[nextIndex])
{
count++;
}
if (a[candidateIndex]==a[nextOfNextIndex])
{
count++;
}
}
count -- ;
return count>a.length/2?candidateIndex:-1;
}
Adding a Java 100/100 O(N) time with O(1) space:
// you can also use imports, for example:
import java.util.Stack;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
int count = 0;
Stack<Integer> integerStack = new Stack<Integer>();
for (int i = 0; i < A.length; i++) {
if (integerStack.isEmpty()) {
integerStack.push(A[i]);
} else if (integerStack.size() > 0) {
if (integerStack.peek() == A[i])
integerStack.push(A[i]);
else
integerStack.pop();
}
}
if (!integerStack.isEmpty()) {
for (int i = 0; i < integerStack.size(); i++) {
for (int j = 0; j < A.length; j++) {
if (integerStack.get(i) == A[j])
count++;
if (count > A.length / 2)
return j;
}
count = 0;
}
}
return -1;
}
}
Here is test result from codility.
I think this question has already been resolved somewhere. The "official" solution should be :
public int dominator(int[] A) {
int N = A.length;
for(int i = 0; i< N/2+1; i++)
{
int count=1;
for(int j = i+1; j < N; j++)
{
if (A[i]==A[j]) {count++; if (count > (N/2)) return i;}
}
}
return -1;
}
How about sorting the array first? You then compare middle and first and last elements of the sorted array to find the dominant element.
public Integer findDominator(int[] arr) {
int[] arrCopy = arr.clone();
Arrays.sort(arrCopy);
int length = arrCopy.length;
int middleIndx = (length - 1) /2;
int middleIdxRight;
int middleIdxLeft = middleIndx;
if (length % 2 == 0) {
middleIdxRight = middleIndx+1;
} else {
middleIdxRight = middleIndx;
}
if (arrCopy[0] == arrCopy[middleIdxRight]) {
return arrCopy[0];
}
if (arrCopy[middleIdxLeft] == arrCopy[length -1]) {
return arrCopy[middleIdxLeft];
}
return null;
}
C#
int dominant = 0;
int repeat = 0;
int? repeatedNr = null;
int maxLenght = A.Length;
int halfLenght = A.Length / 2;
int[] repeations = new int[A.Length];
for (int i = 0; i < A.Length; i++)
{
repeatedNr = A[i];
for (int j = 0; j < A.Length; j++)
{
if (repeatedNr == A[j])
{
repeations[i]++;
}
}
}
repeatedNr = null;
for (int i = 0; i < repeations.Length; i++)
{
if (repeations[i] > repeat)
{
repeat = repeations[i];
repeatedNr = A[i];
}
}
if (repeat > halfLenght)
dominant = int.Parse(repeatedNr.ToString());
class Program
{
static void Main(string[] args)
{
int []A= new int[] {3,6,2,6};
int[] B = new int[A.Length];
Program obj = new Program();
obj.ABC(A,B);
}
public int ABC(int []A, int []B)
{
int i,j;
int n= A.Length;
for (j=0; j<n ;j++)
{
int count = 1;
for (i = 0; i < n; i++)
{
if ((A[j]== A[i] && i!=j))
{
count++;
}
}
int finalCount = count;
B[j] = finalCount;// to store the no of times a number is repeated
}
// int finalCount = count / 2;
int finalCount1 = B.Max();// see which number occurred max times
if (finalCount1 > (n / 2))
{ Console.WriteLine(finalCount1); Console.ReadLine(); }
else
{ Console.WriteLine("no number found"); Console.ReadLine(); }
return -1;
}
}
In Ruby you can do something like
def dominant(a)
hash = {}
0.upto(a.length) do |index|
element = a[index]
hash[element] = (hash[element] ? hash[element] + 1 : 1)
end
res = hash.find{|k,v| v > a.length / 2}.first rescue nil
res ||= -1
return res
end
#Keith Randall solution is not working for {1,1,2,2,3,2,2}
his solution was:
element x;
int count ← 0;
For(i = 0 to n − 1) {
if(count == 0) { x ← A[i]; count++; }
else if (A[i] == x) count++;
else count−−;
}
Check if x is dominant element by scanning array A
I converted it into java as below:
int x = 0;
int count = 0;
for(int i = 0; i < (arr.length - 1); i++) {
if(count == 0) {
x = arr[i];
count++;
}
else if (arr[i] == x)
count++;
else count--;
}
return x;
Out put : 3
Expected: 2
This is my answer in Java: I store a count in seperate array which counts duplicates of each of the entries of the input array and then keeps a pointer to the array position that has the most duplicates. This is the dominator.
private static void dom(int[] a) {
int position = 0;
int max = 0;
int score = 0;
int counter = 0;
int[]result = new int[a.length];
for(int i = 0; i < a.length; i++){
score = 0;
for(int c = 0; c < a.length;c++){
if(a[i] == a[c] && c != i ){
score = score + 1;
result[i] = score;
if(result[i] > position){
position = i;
}
}
}
}
//This is just to facilitate the print function and MAX = the number of times that dominator number was found in the list.
for(int x = 0 ; x < result.length-1; x++){
if(result[x] > max){
max = result[x] + 1;
}
}
System.out.println(" The following number is the dominator " + a[position] + " it appears a total of " + max);
}
The following is NOT a homework problem, it's just a set of problems that I've been working through for practice and I was wondering if anybody else could figure it out:
http://codingbat.com/prob/p159339
Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3's, but every other number may move. The array contains the same number of 3's and 4's, every 3 has a number after it that is not a 3 or 4, and a 3 appears in the array before any 4.
*SOLVED - here is my working code:
public int[] fix34(int...nums)
{
int[] returnArray = new int[nums.length];
//ASSIGN ARRAY
//We know that all 3's can't be moved, and after every 3 there
//will automatically be a 4
for(int i = 0; i<nums.length; i++)
{
if(nums[i] == 3)
{
returnArray[i] = 3;
returnArray[i+1] = 4;
}
}
//REBUILD ARRAY - UNMOVED INDEXES
//If a value was not moved/affected by the above, it will get placed into the array
//in the same position
for (int i = 0; i < nums.length; i++)
{
if (returnArray[i] != 3 && returnArray[i] != 4 && nums[i] != 3 && nums[i] != 4)
{
returnArray[i] = nums[i];
}
}
//REBUILD ARRAY - MOVED INDEXES
//changed values = 0 in returnArray, as a result, any time we hit a 0 we
//can simply assign the value that was in the 4's place in the nums array
OuterLoop: for (int i = 0; i < nums.length; i++)
{
if (returnArray[i] == 0)
{
for (int n = 0; n < returnArray.length; n++)
{
if (returnArray[n] == 4)
{
returnArray[i] = nums[n];
continue OuterLoop;
}
}
}
}
return returnArray;
}
I don't know java, but maybe I can help anyway. i dont want to give you the solution, but think of it like this:
you can move every number that isn't a 3. that's our only limit. that being said:
the only spots you need to change are the spots following 3s....so....every time you loop through, your program should be aware if it finds a spot after a 3 that isn't a 4....
it should also be aware if it finds any 4s not preceded by a 3......
during each loop, once it's found the location of each of those two things, you should know what to do.
Initialize all the variables
for(int i = 0; i<n-1; i++)
{
if(arr[i] == 3)
{
if(arr[i+1] == 4)
continue;
else
{
temp = 0;
while(arr[temp] != 4)
temp++;
//Write your own code here
}
//Complete the code
}
I have NOT provided the entire code. Try completing it as you said it was for your practice.
public int[] fix34(int[] nums) {
int[] arr = new int[nums.length];
int index = 0;
int tempVal= 0,j=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==3){
arr[i] = nums[i];
index=i+1;
tempVal = nums[i+1];
j=index;
while(j<nums.length){
if(j<nums.length && nums[j]==4){
//System.out.println(j+"\t="+nums[j]);
nums[j]=tempVal;
nums[index] = 4;
break;
}
j++;
}
tempVal=0;
index=0;
}else{
arr[i] = nums[i];
}
}
index =0;
for(int i=0;i<nums.length;i++){
if(nums[i]==3 && nums[i+1]==4){
i+=1;
}else if(nums[i]==4){
index = i;
j=index;
while(j<nums.length){
if(nums[j]==3 && nums[j+1]!=4){
arr[index] = nums[j+1];
arr[j+1] = 4;
}
j++;
}
}
}
return arr;
}
Here's mine: A little overkill, but is always right, anyways i make 2 additional arrays and I make 2 passes in the loop putting the correct elements in the correct places. See Logic Below.
public int[] fix34(int[] nums) {
int index1 = 0;
int index2 = 0;
int index3 = 0;
int[] only4 = fours(nums); //holds all 4's in nums
int[] misc = new int[count4(nums)]; //will hold numbers after 3
for(int a = 0; a < nums.length - 1; a++){
if(nums[a] == 3){
misc[index1] = nums[a + 1]; //get it for later use
index1++;
nums[a + 1] = only4[index2]; //now the number after 3 is a 4, from the
index2++; //only4 array
}
}
for(int b = 1; b < nums.length; b++){
if(nums[b] == 4 && nums[b - 1] != 3){ //finds misplaced 4's
nums[b] = misc[index3]; //replaces lone 4's with the
index3++; //right hand side of each 3 original values.
}
}
return nums;
}
public int count4(int[] nums){
int cnt = 0;
for(int e : nums){
if(e == 4){
cnt++;
}
}
return cnt;
}
public int[] fours(int[] nums){
int index = 0;
int[] onlyFours = new int[count4(nums)]; //must set length
for(int e : nums){
if(e == 4){
onlyFours[index] = e;
index++;
}
}
return onlyFours;
}
I solved mine using two ArrayLists which contain the places of 3's and 4's.
I hope this helps.
public int[] fix34(int[] nums)
{
//Create a copy of nums to manipulate.
int[] ret = nums;
//Create two ArrayLists which carry corresponding places of 3 and 4;
ArrayList<Integer> threePositions = new ArrayList<Integer>();
ArrayList<Integer> fourPositions = new ArrayList<Integer>();
//Get the places of 3 and 4 and put them in the respective ArrayLists.
for (int i = 0; i < ret.length; i++)
{
if (ret[i] == 3)
{
threePositions.add(i);
}
if (ret[i] == 4)
{
fourPositions.add(i);
}
}
//Swap all ints right after the 3 with one of the 4s by using the referenced
//ArrayLists values.
for (int i = 0; i < threePositions.size(); i++)
{
int temp = ret[threePositions.get(i) + 1];
ret[threePositions.get(i) + 1] = ret[fourPositions.get(i)];
ret[fourPositions.get(i)] = temp;
}
//Return the ret array.
return ret;
}