How to optimise this code of sorting,this is not exeuting within the time limits.This question is from hackerrank [closed] - c++

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 2 years ago.
Improve this question
How to reduce the time compexity of this code,this is not exeuting within the time
exact ques from hackerrank--
Complete the circularArrayRotation function in the editor below. It should return an array of integers representing the values at the specified indices.
circularArrayRotation has the following parameter(s):
a: an array of integers to rotate
k: an integer, the rotation count
queries: an array of integers, the indices to report
vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
int i,temp;
vector<int> ans;
//to perform number of queries k
while(k--)
{ //shift last element to first pos and then move rest of elements to 1 postion forward
temp=a[a.size()-1]; //last element
for(i=a.size()-1;i>0;i--)
{
a[i]=a[i-1];
}
a[0]=temp;
}
for(i=0;i<queries.size();i++)
{
ans.push_back(a[queries[i]]);
}
return ans;
}

The vector a is being rotated by k in the while loop. The whole loop can be removed by adding k and using modulo when accessing elements in a:
ans.push_back(a[(queries[i]+k)%a.size()]);
Note: you might need handling of negative values of k.
Note: Maybe it should be minus instead of plus.
An alternative could be to use std::rotate.
Furthermore, the ans vector should be pre-allocated to reduce the number of allocations to one:
ans.reserve(queries.size());

Related

Issue with leet code problem 3 Longest substring [closed]

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 months ago.
Improve this question
Essentially we are asked to find, given a string, the longest substring with no repeating characters, below I am using the sliding window approach.
Examples:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
My attempt:
class Solution {
public:
int lengthOfLongestSubstring(std::string s){
int count{0};
std::map<char,int> char_map;
std::vector<char> char_vec;
auto left{char_vec.begin()};
auto right{char_vec.begin()};
for(int i = 0; i < s.length(); i++){
char_vec.push_back(s[i]);
if(char_map.find(s[i]) != char_map.end()){
char_map[s[i]]++;
}
else{
char_map.insert(std::pair<char,int>{s[i],1});
}
while(++right != char_vec.end() && char_map[*(right)] > 1){
char_map[*(left++)]--;
}
count = (count < std::distance(left,right)) ? std::distance(left,right) : count;
}
return count;
}
};
However, there is an issue in the while loop near the end of the code block that is causing
compiler error and am very confused about how to solve it.
So your code is suffering from iterator invalidation. Here you have a vector
std::vector<char> char_vec;
and here you create two iterators to that vector
auto left{char_vec.begin()};
auto right{char_vec.begin()};
and then here you add an item to that vector
char_vec.push_back(s[i]);
When you add an item to a vector you may invalidate any iterators to that vector, and any use of such iterators causes your program to have undefined behaviour.
Instead of using iterators you could try using offsets (i.e. integer variables which you use to index the vector). These have the advantage that they are not invalidated as the vector grows.
For more information on iterator invalidation see the table on this page. Different containers have different behaviour wrt iterator invalidation.

Explain the algorithm in detail [closed]

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 2 years ago.
Improve this question
int Min[m];
for(int i=0; i<m;i++){
int Min_Element=INT_MAX;
for(int j=0;j<n;j++){
Min_Element = min ( Min_Element , Target[i][j]);
}
Min[i]=Min_Element;
}
Can someone tell me the whole explaination about the algorithm above to me please..
I still can't figure out the detail about how the Min_Element = min ( Min_Element , Target[i][j]); works..
This may help
int Min[m]; // store minimum value for each row
for(int i=0; i<m;i++){ // loop each row
int Min_Element=INT_MAX; // start at max value
for(int j=0;j<n;j++){ // for each number in row
Min_Element = min ( Min_Element , Target[i][j]); // set minimum value if less than current minimum
}
Min[i]=Min_Element; // minimum value for row
}
It looks for the minimal element of each row (indexed by i) by comparing each column of a matrix (target[i][j]) to a temporary minimal value (initialized with a very large number to make sure it gets discarded by values stored in the matrix).

How to iterate over unique elements in an array in c++ [closed]

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
Suppose I have the following array:
int arr[7] = {18,16,5,5,18,16,4}
How can I iterate over unique elements(18, 16, 5 and 4) in a loop in the same order in which they occur?
I could use a set but then the order of the iteration would change(set stores elements in ascending order).
What is the fastest solution to this problem?
Iterate over the array and store the numbers you have already seen in a set. For each iteration you check whether the number is already in the set or not. If yes, skip the current element. If not, process it and insert it into the set.
Also note that you want an std::unordered_set and not a std::set which is ordered. Order doesn't matter for your filtering set.
If the values are in a known limited range, you can use a lookup table. Create an array with bool elements, sized to maximum value + 1. Use the values of the first array as index into the bool array.
#include <iostream>
int main() {
int arr[7] = {18,16,5,5,18,16,4};
constexpr int maxValue = 18;
bool lookup[maxValue + 1]{};
for( auto i : arr )
{
if( ! lookup[ i ] )
{
std::cout << i << ' ';
lookup[ i ] = true;
}
}
}
Live Demo
A std::bitset would be more space efficient but also slower, because individual bits cannot be directly addressed by the CPU.
Simply replace the bool array like so:
std::bitset<maxValue + 1> lookup;
The remaining code stays the same.
Live Demo

Code complexity [closed]

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
Can anybody explain to me the time complexity of the following code:
cin >> n;
while(n>9)
{
int num = n;
int s = 0;
while(num!=0)
{
s = s + num%10;
num = num/10;
}
n = s;
}
cout<<n<<endl;
The above code calculates the sum of the digits of the number until the sum becomes a single digit number.
Example: 45859 = 4+5+8+5+9 = 31 = 3+1 = 4
Edit: I think that the inner loop calculating the sum of digits has O(log_base_10(n)) complexity, but the outer loop continues till the sum obtained so far is less than 10. So the total complexity depends on how many times the outer loop is going to run.. I am not able to figure that out... Some kind of mathematical gimmicks to calculate the complexity of the outer loop would help!!!
You are calculating the sum of the digits. The number of digits in n scales with log(n).

How can I scale an array to new array of different size [closed]

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 an array of integer, and it's length is fixed, and the array contains 0 or 1. And I need to scale this array to new array with different size and it's size can be less than or greater than input.
For example,
input = 1,0,1,0,1 //input size 5
output = 1,1,0,0,1,1,0,0,1,1 //out put size 10
The problem comes here, suppose the input is repeat of 1 and 0 in random order, I need to scale to new array of different size, how it's possible?.
Like
input 1,0,1,1,1,0,1,0,0,0......// n size random repeat of 0 and 1
output ?,?,?.....................// of m
Actually I have to plot the input array in graph , the input array will be fixed length, and I need to scale this array to another array of different size, as I have to plot for different screen size.
Following may help: (https://ideone.com/xS1f0C)
template <std::size_t N, std::size_t M>
void normalizebyIndex(const int (&src)[N], int (&dest)[M])
{
for (std::size_t i = 0; i != M; ++i) {
dest[i] = src[i * N / M];
}
}