Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
public int solution(int[] A) {
// A - array of bulbs. A[i] its position in row.
// return number of moments where all turned on bulbs are shined
// start from 0 to length-1, switch on bulbs ( A[i] represents a bulb's position)
// A[i] bulb shined if: 1) A[i] is switched 2) 1..A[i]-1 all are shined
// examples:
// input: {1,2,3,4,5} output: 5
// input: {1} output: 1
// input: {2,3,4,1,5} output: 2
// input: {2,1,3,5,4} output: 3
}
I suggested to iterate i: from 0 to a length-1, save every A[i] in a SortedSet. Check if there are i-1 elements in headSet < A[i]. If yes - we A[i] is shined.
It seems the performance of the solution above is low...
Can anybody suggest better?
You could do it in O(n):
public int solution(int[] a) {
Set<Integer> missing = new HashSet<>();
Set<Integer> store = new HashSet<>();
int count = 0;
for (int i = 0; i < a.length; i++) {
if (!store.contains(i + 1) && i + 1 != a[i])
missing.add(i + 1);
if (i + 1 < a[i])
store.add(a[i]);
else
missing.remove(a[i]);
if (missing.isEmpty())
count++;
}
return count;
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Today I am solving hackerrank problem and unfortunately, I am stuck on this. Actually, I passed 4 test cases but the rest test case shows runtime error..
Here is my code -
public static String leftrotate(String str, int d) {
String ans = str.substring(d) + str.substring(0, d);
return ans;
}
public static String rightrotate(String str, int d) {
return leftrotate(str, str.length() - d);
}
public static int maximumPower(String s) {
int size = s.length();
int arr[] = new int[size];
for(int i = 0; i < size; i++){
arr[i] = Integer.parseInt(rightrotate(s, i), 2);
}
int max = 0;
for(int i = 0; i < size; i++){
for(int j = 1; j < size; j++){
if(arr[i] % Math.pow(2, j) == 0){
//System.out.println(arr[i] + "power = " +Math.pow(2, j));
if(max < j){
max = j;
}
}
}
}
return max;
}
What means dividable by the largest power of 2?
xyz10000
is dividable by
10000
So a 1 fby 0s. Otherwise it would not be dividable.
If there is no 1, the result is -1.
For rotatation equivalence, you are looking for the longest sequence of 0s which might be situated at front and tail of the sequence.
Now java's BitSet can juggle with bit operations, like find the next bit 1 from a given position.
To recap:
Look at the abstract problem, find the logic
Pick the data structure
Code it
Especially step 1 is very illuminating, yielding a very simple problem.
The key phrase being "the longest sequence of zeros."
I hope I did not spoil the coding.
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 6 years ago.
Improve this question
What will be the Big Oh of these portion of codes:
int sum = 0;
for(int i = 1; i < N; i *= 2)
for(int j =0; j <i; j++)
sum++;
And
int sum = 0;
for(int i = 0; i < N; i *= 2)
for(int j =0; j <i; j++)
sum++;
My Attempt:
According to me both have time complexity equal to O(n^2), because here we will multiply n with n which is equal to n^2. Am I correct? Or doing some mistake?
For the first portion of code:
1st loop will go from 1 to n with variable i going as
1, 2, 4, 8, 16.... n
and in the second loop j goes from 0 to i so the time complexity will be
O(1 + 2 + 4 + 8 + 16.... n) = O(2n - 1) = O(n)
and as for the second portion of code
i starts from 0, it always be 0 because you are multiplying it by 2. Its an infinite loop.
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 7 years ago.
Improve this question
I am trying to design an algorithm that, given a list of n elements, finds the min and max in 3n / 2 comparisons. Any hints on how to do this?
As a hint, imagine that all the array elements are players in an elimination tournament. Pair off all the players and have the "winners" (bigger numbers) advance to one tournament and the "losers" (smaller numbers) fall into a loser's bracket. You will now have n / 2 winners to consider, and the maximum value must be one of them, and n / 2 losers to consider, and the minimum value must be one of them. In the process of doing this, you made n / 2 comparisons. Can you use n remaining comparisons to find the minimum of one group and the maximum of the other?
#templatetypedef 's hint is right:
public static void findMinimumAndMaximumOf(int[] numbers) {
assert numbers.length >= 2;
List<Integer> bigList = new ArrayList<>(numbers.length / 2);
List<Integer> smallerList = new ArrayList<>(numbers.length / 2);
int i = 1;
for (; i < numbers.length; i = i + 2) {
if (numbers[i] > numbers[i - 1]) {
bigList.add(numbers[i]);
smallerList.add(numbers[i - 1]);
} else {
bigList.add(numbers[i - 1]);
smallerList.add(numbers[i]);
}
}
if ((numbers.length & 1) == 1) {
if (numbers[numbers.length - 1] > numbers[numbers.length - 2]) {
bigList.add(numbers[numbers.length - 1]);
} else {
smallerList.add(numbers[numbers.length - 1]);
}
}
Iterator<Integer> iBig = bigList.iterator();
int biggest = iBig.next();
while (iBig.hasNext()) {
int current = iBig.next();
if (current > biggest) {
biggest = current;
}
}
Iterator<Integer> iSmall = smallerList.iterator();
int smallest = iSmall.next();
while (iSmall.hasNext()) {
int current = iSmall.next();
if (current < smallest) {
smallest = current;
}
}
System.out.println(String.format("Max:%d, Min:%d" ,biggest,smallest));
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a sequence, which can be really long.
I am inputing the number of elements and the special number, which will cut my sequence into the parts, for example:
10 2
here I have 10 numbers and 5 blocks (10/2)
I must sort this sequence using merge sort
here is the code:
int number_of_elements, k;
cin >> number_of_elements;
cin >> k;
int* massiv_1 = new int[k];
int* massiv_2 = new int[k];
int* resulted_massiv = new int[number_of_elements];
for(int i = 0; i < number_of_elements; i++) {
resulted_massiv[i] = 0;
}
int i = 0;
while( i < number_of_elements) {
int counter_1 = 0;
int counter_2 = 0;
cin >> massiv_1[counter_1];
counter_1++;
if( i != 0 ) {
quick_Sort( massiv_1, k-1 );
for(; counter_2 < k; counter_2++) {
cin >> massiv_2[counter_2];
counter_2++;
}
quick_Sort( massiv_2, k-1 );
merge(massiv_1, k, massiv_2, k, resulted_massiv, i);
}
counter_1 = 0;
counter_2 = 0;
i = i + k;
}
here is the merge sort
void merge(int *a, int a_len, int *b, int b_len, int *c, int z1) {
int i = 0, j = 0;
for(;i < a_len && j < b_len;) {
if(a[i] < b[j]) {
c[z1] = a[i];
++i;
} else {
c[z1] = b[j];
j++;
}
}
if(i == a_len) {
for(; j < b_len; ++j) {
c[z1] = b[j];
}
} else {
for(; i < a_len; ++i) {
c[z1] = a[i];
}
}
}
In other words here is the algorithm:
First I cut sequnce into k parts
I am going through it, if I see the index = k, I am using quick_sort,
then I go to the nearest block and also use quick_sort,
and then I am using merge sorting puting it into other array
...and this I am doing till the end of the sequence
this algorithm doesn't work, if enter this:
10 4
0 4 3 2 1 8 7 6 5 9
it must sort this sequence, but it shows this:
0 0 0 0 4 0 0 0 8 0
I can't get it
I will really appreciate your help, thank you in advance!!!
You always write in single c[z1] element in merge function, and never increment z1 index.
Index in "c" array should be incremented at every step, so you can use c[z1++] everywhere in the funcion
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have been asked this question in an interview. In 1 million numbers, all numbers have a duplicate except for one number. How to find that one number? Which algorithm should I use to get a good time and space complexity? I got an idea to use EXOR gate but I'm still lagging in deploying that.
Use xor for all numbers sequentially.
For following list of numbers:
1, 2, 3, 4, 3, 2, 1
Let ^ represents the exclusive disjunction (or xor)
Then,
1 ^ 2 ^ 3 ^ 4 ^ 3 ^ 2 ^ 1 = 4
Another simple solution: Two bitsets can be used, one for marking the existance of a number and another to mark duplication. We iterate through the array amd mark each element for existence and duplication. Then we iterate through the bitsets to find a number that is marked for existence and but not marked for duplication.
int[] numbers = new int[] { 1, 1, 2, 2, 3, 4, 4, 5, 5 };
BitSet bs1 = new BitSet();
BitSet bs2 = new BitSet();
int largestNumber = 0;
for (int i = 0; i < numbers.length; i++) {
int number = numbers[i];
if (bs1.get(number) == false) {
// Mark for existence
bs1.set(number);
} else {
// Mark for duplicating
bs2.set(number);
}
if (number > largestNumber) {
largestNumber = number;
}
}
for (int i = 0; i <= largestNumber; i++) {
if (bs1.get(i) && !bs2.get(i)) {
System.out.println("Non duplicating number is: " + i);
}
}
}
try this
int[] a = {1, 2, 1, 2, 3};
Arrays.sort(a);
for(int i = 0; i < a.length; i++) {
if (i == 0 && a[i] != a[i + 1] || i == a.length -1 || a[i] != a[i - 1] && a[i] != a[i + 1]) {
System.out.println(a[i]);
break;
}
}
Following may solve you problem:
Complexity: O(N)
// Assuming the duplicate are going by pair
// x ^x == 0 and x ^0 == x
int find_unique(const std::vector<int>& v)
{
assert(v.size() % 2 == 1);
int res = 0;
for (auto value : v) {
res ^= value;
}
return res;
}
Or
Complexity: O(N log N)
int find_unique(std::vector<int>& v)
{
if (v.empty()) { throw std::runtime_error("empty vector"); }
std::sort(v.begin(), v.end());
auto it = std::unique(v.begin(), v.end());
if (it == v.begin()) { throw std::runtime_error("no unique number"); }
if (it != v.begin() + 1) { throw std::runtime_error("several unique numbers"); }
return v[0];
}
or
Complexity: O(N log N)
int find_unique(std::vector<int>& v)
{
if (v.empty()) { throw std::runtime_error("empty vector"); }
if (v.size() == 1) { return v[0]; }
std::sort(v.begin(), v.end());
if (v[0] != v[1]) { return v[0]; }
for (int i = 1, size = v.size(); i + 1 < size; ++i) {
if (v[i] == v[i - 1]) { continue; }
if (v[i] == v[i + 1]) { ++i; continue; } // we may skip v[i + 1]
return v[i];
}
return v.back();
}
I believe that if we combine quicksort(search) technique and xor, we could get the fastest possible code. I am trying though, but correct me if this idea is wrong meanwhile.
BTW, this has good number of usecases though. Though the question is language agnostic, and requires clear algorithm, I am mentioning some use cases readers might find useful.
0's can be duplicate... or negative numbers...
System.out.println(33 ^ 33 ^ 7 ^ 0 ^ 0 ^ 5 ^ 7 ^ 5); is giving 0 (0 is a duplicate here)
Duplicates might be more than 2:
System.out.println(1 ^ 1 ^ 2 ^ 3 ^ 3 ^ 3); is giving 1, instead of 2...
And on and on, the question would possibly be complex than we might first think.
For a large number of input items (as opposed to the examples with a few numbers) it should take a considerable amount of time getting the input into some data structure. I was thinking about using this necessary time as part of the computation process by putting it into a map. The value of the map will only be one for the one single number. I assume the data is correct so I omit checking for that, but if there are multiple numbers which occur only one time it will just return the first one.
There should be room for further optimization, e.g. by accessing the map by value and just look for the one which has 1. I think this could be done easily with Boost.Bimap.
int getSingleNumber(){
map<int, int> numbers;
for (all input items)
{
numbers[currentInputItem]++;
}
for( map<int,int>::iterator ii=numbers.begin(); ii!=numbers.end(); ++ii)
{
if ( (*ii).second == 1 ) return (*ii).first;
}
}