Runtime error in Cyclic Binary String Question [closed] - data-structures

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.

Related

Maximum subArray product using Divide and Conquer Anyone?

I am aware that this is one of the most common coding questions when it comes to integral arrays. I am looking for a solution to the problem of finding the longest contiguous subArray product within the array, but using a Divide and Conquer approach.
I split my input array into two halves: the left and right arrays are solved recursively in case the solution falls entirely in the half array. Where I have a problem is with the scenario where the subArray crosses the mid-point of the array. Here is a short snippet of my code for the function handling the crossing:
pair<int,pair<int, int>> maxMidCrossing(vector<int>& nums, int low, int mid, int high)
{
int m = 1;
int leftIndx = low;
long long leftProduct = INT_MIN;
for(int i = mid-1; i>= low; --i)
{
m *= nums[i];
if(m > leftProduct) {
leftProduct = m;
leftIndx = i;
}
}
int mleft = m;
m=1;
int rightIndx = high;
long long rightProduct = INT_MIN;
for(int i = mid; i<= high; ++i)
{
m *= nums[i];
if(m > rightProduct) {
rightProduct = m;
rightIndx = i;
}
}
int mright = m;
cout << "\nRight product " << rightProduct;
pair<int, int> tmp;
int maximum = 0;
// Check the multiplication of both sides of the array to see if the combined subarray satisfies the maximum product condition.
if(mleft*mright < leftProduct*rightProduct) {
tmp = pair(leftIndx, rightIndx);
maximum = leftProduct*rightProduct;
}
else {
tmp = pair(low, high);
maximum = mleft*mright;
}
return pair(maximum, tmp);
}
The function handling the entire search contains the following:
auto leftIndx = indexProduct(left);
auto rightIndx = indexProduct(right);
auto midResult = maxMidCrossing(nums, 0, mid, nums.size()-1); // middle crossing
//.....more code........
if(mLeft > midProduct && mLeft > mRight)
tmp=leftIndx;
else if (mRight > midProduct && mRight > mLeft)
tmp = pair(rightIndx.first + mid, rightIndx.second + mid);
else tmp=midIndx;
In the end, I just compute the maximum product across the 3 scenarios: left array, crossing array, right array.
I still have a few corner cases failing. My question is if this problem admits a recursive solution of the Divide and Conquer type, and if anyone can spot what I may be doing wrong in my code, I would appreciate any hints that could help me get unstuck.
Thanks,
Amine
Take a look at these from leetcode
C++ Divide and Conquer
https://leetcode.com/problems/maximum-product-subarray/discuss/48289/c++-divide-and-conquer-solution-8ms
Java
https://leetcode.com/problems/maximum-product-subarray/discuss/367839/java-divide-and-conquer-2ms
c#
https://leetcode.com/problems/maximum-product-subarray/discuss/367839/java-divide-and-conquer-2ms

How can I find the max depth of a graph with recursive code of depth of search?

I solved the problem with the iterative approach but having a hard time applying the recursive approach to find the max depth of a graph.
Here is the codeforces question https://codeforces.com/problemset/problem/115/A
It needs the max depth of the graph as the solution, I guess. How, can I solve it.
according to the question you get one or more (it not said that only one employee get a -1) trees.
But i think the problem is quite simple. As you found out the max depth of the tree(s) should be the number of groups.
So after parsing the input into an array the solution would just be:
int employees[n];
int maxdepth = 0
for (int i = 0; i<n; ++i){
int thisDepth = 0;
int t = i;
while(employees[t] != -1)
t = employees[t];
thisDepth++;
}
if(thisDepth > maxDepth){
maxDepth = thisDepth;
}
}
A recursive approach would look like:
int getDepth(const int i_employeeArray[], int i_employee){
if( i_employeeArray[i_employee] == -1 ){
return 0;
} else {
return 1+ getDepth(i_employeeArray, i_employeeArray[i_employee]);
}
}
int employees[n];
int maxdepth = 0
for (int i = 0; i<n; ++i){
int thisDepth = getDepth(employees, i);
if(thisDepth > maxDepth){
maxDepth = thisDepth;
}
}
Both could be optimizedby storing calculated depths for visited fields, but should not be necessary for this rather small (<=2000 employees) problem.

CodeFight firstDuplicate interview challenge

As per problem statement:
Write a solution with O(n) time complexity and O(1) additional space
complexity. Given an array a that contains only numbers in the range
from 1 to a.length, find the first duplicate number for which the
second occurrence has the minimal index. In other words, if there are
more than 1 duplicated numbers, return the number for which the second
occurrence has a smaller index than the second occurrence of the other
number does. If there are no such elements, return -1
I followed my code according to constraints and still I'm getting time complexity error. Here's my solution:
int firstDuplicate(std::vector<int> a)
{
long long int n = a.size();
int cnt=0;
for(long long int i=0;i<n;i++)
{
//cout<<a[i]<<" "<<cnt<<endl;
if(a[i]==n||a[i]==-n)
{ cnt++;
if(cnt>1)
return n;
}
else if(a[abs(a[i])]<0)
return -a[i];
else
a[a[i]] = -a[a[i]];
}
return -1;
}
Can anyone suggest me better algorithm or whats wrong with this algorithm?
The algorithm for this problem is as follows:
For each number in the array, a, each time we see that number, we make a[abs(a[i]) - 1] negative. While iterating through a, if at some point we find that a[abs(a[i] - 1] is negative, we return a[i]. If we reach the last item in the array without finding a negative number, we return -1.
I feel like, this is what you were trying to get at, but you might have overcomplicated things. In code this is:
int firstDuplicate(std::vector<int> a)
{
for (int i = 0; i < a.size(); i += 1)
{
if (a[abs(a[i]) - 1] < 0)
return abs(a[i]);
else
a[abs(a[i]) - 1] = -a[abs(a[i]) - 1];
}
return -1;
}
This runs in O(n) time, with O(1) space complexity.
You can use the indexes to mark whether an element has occured before or not, if the value at idx is negative then it has already occurred before
int firstDuplicate(std::vector<int> a)
{
long long int n = a.size();
int cnt=0;
for(long long int i=0;i<n;i++)
{
int idx = a[i] - 1;
if(a[idx] < 0){
return a[i];
}
a[idx] *= -1;
}
return -1;
}

Find the first prime fibonacci number larger than a given minimum [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to solve a problem but getting segmentation fault , not able to find what is wrong
the problem is you have to find the first fibonacci number greater then 227000 which is also a prime , call it X and return the sum of all prime divisors of X+1
#include<iostream>
int main(){
int n = 227000;
int prime[1000000];
std::cout<<"lll";
int i;
for(i = 2; i<1000;i++){
if(!prime[i]) continue;
int j;
for(j=i*i;j<1000000;j+=i){
prime[j] = 0;
}
}
int num = 1;
int nextnum = 1;
int newnum;
while(1){
newnum = num+nextnum;
if(newnum>n && prime[newnum]) break;
num = nextnum;
nextnum = newnum;
}
int sum = 1;
for(int i=2;i<1000000;i++){
if(prime[i] && newnum%i==0){
sum+=i;
}
}
std::cout<<sum;
return 0;
}
One reason you may get a segmentation fault is that you are getting a stack overflow due to placing 1 million integers on the stack.
Another reason is that primes is not initialised so the while loop may go too far and access primes beyond the limits of the array.
To fix this you need to:
Allocate array on the heap (or simply change it to be global)
Initialise your primes array to contain 1's
It would be better if the while loop also guaranteed to terminate or you may access the prime array beyond bounds.
#include<iostream>
int prime[1000000];
int main(){
int n = 227000;
std::cout<<"lll";
int i;
for(i = 2; i<1000000;i++)
prime[i]=1;
for(i = 2; i<1000;i++){
if(!prime[i]) continue;
int j;
for(j=i*i;j<1000000;j+=i){
prime[j] = 0;
}
}
int num = 1;
int nextnum = 1;
int newnum;
while(1){
newnum = num+nextnum;
if(newnum>n && prime[newnum]) break;
num = nextnum;
nextnum = newnum;
}
int sum = 1;
for(int i=2;i<1000000;i++){
if(prime[i] && newnum%i==0){
sum+=i;
}
}
std::cout<<sum;
return 0;
}
UPDATE
By the way, the second loop pointlessly tries to find factors of a prime number newnum.
I suspect the problem is actually to find something like the prime factors of the number (newnum+1) for which the code would change to
int sum = 0;
for(int i=2;i<1000000;i++){
if(prime[i] && (newnum+1)%i==0){
sum+=i;
}
}
I would creating a loop to generate Fibonacci numbers until I found one larger than the input. Then I would check each to see if it's prime. It's much faster than generating a list of prime numbers.
#include<iostream>
#include<math.h>
bool isPrime(int number)
{
for (int i=2;i<=sqrt(number);i++)
if ((number%i)==0) return false;
return true;
}
int main(){
int n = 227000;
int index=1;
int nums[2];
nums[0]=0;
nums[1]=1;
int currentFib = 0;
while (currentFib <=n || !isPrime(currentFib))
{
//Calculate the next fib
index = (index+1)%2;
nums[index] = nums[0]+nums[1];
currentFib = nums[index];
cout<<"Fibb "<<currentFib<<endl;
}
return currentFib;
}
Code returned 514229, which is both prime and a Fibonacci number and greater than 227000.
The prime fibonacci numbers are given at A005478. The smallest prime fibonacci number greater than 227000 is 514229. You might enjoy this entry at my blog.

Old Top Coder riddle: Making a number by inserting +

I am thinking about this topcoder problem.
Given a string of digits, find the minimum number of additions required for the string to equal some target number. Each addition is the equivalent of inserting a plus sign somewhere into the string of digits. After all plus signs are inserted, evaluate the sum as usual.
For example, consider "303" and a target sum of 6. The best strategy is "3+03".
I would solve it with brute force as follows:
for each i in 0 to 9 // i -- number of plus signs to insert
for each combination c of i from 10
for each pos in c // we can just split the string w/o inserting plus signs
insert plus sign in position pos
evaluate the expression
if the expression value == given sum
return i
Does it make sense? Is it optimal from the performance point of view?
...
Well, now I see that a dynamic programming solution will be more efficient. However it is interesting if the presented solution makes sense anyway.
It's certainly not optimal. If, for example, you are given the string "1234567890" and the target is a three-digit number, you know that you have to split the string into at least four parts, so you need not check 0, 1, or 2 inserts. Also, the target limits the range of admissible insertion positions. Both points have small impact for short strings, but can make a huge difference for longer ones. However, I suspect there's a vastly better method, smells a bit of DP.
I haven't given it much thought yet, but if you scroll down you can see a link to the contest it was from, and from there you can see the solvers' solutions. Here's one in C#.
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
public class QuickSums {
public int minSums(string numbers, int sum) {
int[] arr = new int[numbers.Length];
for (int i = 0 ; i < arr.Length; i++)
arr[i] = 0;
int min = 15;
while (arr[arr.Length - 1] != 2)
{
arr[0]++;
for (int i = 0; i < arr.Length - 1; i++)
if (arr[i] == 2)
{
arr[i] = 0;
arr[i + 1]++;
}
String newString = "";
for (int i = 0; i < numbers.Length; i++)
{
newString+=numbers[i];
if (arr[i] == 1)
newString+="+";
}
String[] nums = newString.Split('+');
int sum1 = 0;
for (int i = 0; i < nums.Length; i++)
try
{
sum1 += Int32.Parse(nums[i]);
}
catch
{
}
if (sum == sum1 && nums.Length - 1 < min)
min = nums.Length - 1;
}
if (min == 15)
return -1;
return min;
}
}
Because input length is small (10) all possible ways (which can be found by a simple binary counter of length 10) is small (2^10 = 1024), so your algorithm is fast enough and returns valid result, and IMO there is no need to improve it.
In all until your solution works fine in time and memory and other given constrains, there is no need to do micro optimization. e.g this case as akappa offered can be solved with DP like DP in two-Partition problem, but when your algorithm is fast there is no need to do this and may be adding some big constant or making code unreadable.
I just offer parse digits of string one time (in array of length 10) to prevent from too many string parsing, and just use a*10^k + ... (Also you can calculate 10^k for k=0..9 in startup and save its value).
I think the problem is similar to Matrix Chain Multiplication problem where we have to put braces for least multiplication. Here braces represent '+'. So I think it could be solved by similar dp approach.. Will try to implement it.
dynamic programming :
public class QuickSums {
public static int req(int n, int[] digits, int sum) {
if (n == 0) {
if (sum == 0)
return 0;
else
return -1;
} else if (n == 1) {
if (sum == digits[0]) {
return 0;
} else {
return -1;
}
}
int deg = 1;
int red = 0;
int opt = 100000;
int split = -1;
for (int i=0; i<n;i++) {
red += digits[n-i-1] * deg;
int t = req(n-i-1,digits,sum - red);
if (t != -1 && t <= opt) {
opt = t;
split = i;
}
deg = deg*10;
}
if (opt == 100000)
return -1;
if (split == n-1)
return opt;
else
return opt + 1;
}
public static int solve (String digits,int sum) {
int [] dig = new int[digits.length()];
for (int i=0;i<digits.length();i++) {
dig[i] = digits.charAt(i) - 48;
}
return req(digits.length(), dig, sum);
}
public static void doit() {
String digits = "9230560001";
int sum = 71;
int result = solve(digits, sum);
System.out.println(result);
}
Seems to be too late .. but just read some comments and answers here which say no to dp approach . But it is a very straightforward dp similar to rod-cutting problem:
To get the essence:
int val[N][N];
int dp[N][T];
val[i][j]: numerical value of s[i..j] including both i and j
val[i][j] can be easily computed using dynamic programming approach in O(N^2) time
dp[i][j] : Minimum no of '+' symbols to be inserted in s[0..i] to get the required sum j
dp[i][j] = min( 1+dp[k][j-val[k+1][j]] ) over all k such that 0<=k<=i and val[k][j]>0
In simple terms , to compute dp[i][j] you assume the position k of last '+' symbol and then recur for s[0..k]

Resources