Big O notation of a specific method - time-complexity

What's the Big O notation of the following method and why?
public int f(int n) {
if (n <= 0) {
return 0;
}
return f(n/2) + n;
}

Related

How to write test cases using Equivalence Class, Boundary value, and Basis Path Testing

I have a method isPerfect(x) (with 4<=x<=10000) below, how to write test cases based on Equivalence Class, Boundary Value, and Basis Path Testing:
public boolean checkPerfectNumber(int x) {
if(x >= 4 && x <= 10000) {
int sum = 0;
for(int i = 1; i < x; i++) {
if(x % i == 0) {
sum += i;
}
}
if(sum == x) return true;
}
return false;
}

What is the time complexity of this function?

Here's a sample solution for Sliding Window Maximum problem in Java.
Given an array nums, there is a sliding window of size k which is
moving from the very left of the array to the very right. You can only
see the k numbers in the window. Each time the sliding window moves
right by one position.
I want to get the time and space complexity of this function. Here's what I think would be the answer:
Time: O((n-k)(k * logk)) == O(nklogk)
Space (auxiliary): O(n) for return int[] and O(k) for pq. Total of O(n).
Is this correct?
private static int[] maxSlidingWindow(int[] a, int k) {
if(a == null || a.length == 0) return new int[] {};
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
// max heap
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
int[] result = new int[a.length - k + 1];
int count = 0;
// time: n - k times
for (int i = 0; i < a.length - k + 1; i++) {
for (int j = i; j < i + k; j++) {
// time k*logk (the part I'm not sure about)
pq.offer(a[j]);
}
// logk
result[count] = pq.poll();
count = count + 1;
pq.clear();
}
return result;
}
You're right in most of the part except -
for (int j = i; j < i + k; j++) {
// time k*logk (the part I'm not sure about)
pq.offer(a[j]);
}
Here total number of executions is log1 + log2 + log3 + log4 + ... + logk. The summation of this series -
log1 + log2 + log3 + log4 + ... + logk = log(k!)
And second thought is, you can do it better than your linearithmic time solution using double-ended queue property which will be O(n). Here is my solution -
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || k <= 0) {
return new int[0];
}
int n = nums.length;
int[] result = new int[n - k + 1];
int indx = 0;
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
// remove numbers out of range k
while (!q.isEmpty() && q.peek() < i - k + 1) {
q.poll();
}
// remove smaller numbers in k range as they are useless
while (!q.isEmpty() && nums[q.peekLast()] < nums[i]) {
q.pollLast();
}
q.offer(i);
if (i >= k - 1) {
result[indx++] = nums[q.peek()];
}
}
return result;
}
HTH.

How is it possible to randomly remove an element from vector< vector<short> >?

Below is a Sudoku initializer, I am attempting to create a function that based on User input, erases a random element from the the board. The random element can be removed from any part of the board.
class cell{
bool m_occu; //occupied is shown '.'
int m_num;
public:
cell() : m_occu(false), m_num(0) {}
void setMark(const int num){m_num = num; m_occu = true;}
bool isMarked() const { return m_occu; }
int getNum(){ return m_num;}
friend ostream& operator << (ostream& o, const cell& c){
if (!c.m_occu) return o << setw(2) << '-';
return o << setw(2) << c.m_num;
}
};
class board {
vector<vector <cell> >m_map;
bool col_row;
public:
board() {
vector<cell> a_row(9);
col_row = false;
for (int i = 0; i < 9; ++i)
{
for(int j = 0; j < 9; j++)
{
a_row[j].setMark(j+1);
}
random_shuffle(a_row.begin(), a_row.end());
m_map.push_back(a_row);
}
}
void erase(){
}
Here is the code for erase function:
void erase(std::vector your_vector){
your_vector.erase(your_vector.begin() + random(1,your_vector.size()));
}
and this the code for random number generation:
int random(int min, int max) //range(min, max)
{
bool first = true;
if ( first )
{
srand(time(NULL)); //seeding only for the first time
first = false;
}
return min + rand() % (max - min);
}

Platform::Collections::Vector sorting

In Metro Style apps sometimes we use Platform::Collections::Vector to hold elements used in a ListView.
How to sort a Platform::Collections::Vector?
I'm aware there are plenty of structures in std that can be sorted but I was wondering if there was some method for Platform::Collections::Vector other than writing your own sort function.
Actually something like the below should also work:
auto vec = ref new Platform::Collections::Vector<T^>();
std::sort(begin(vec), end(vec));
I didn't find any suitable answer so I used this workaround.
It's a simple quicksort over a Platform::Collections::Vector
void swap (Platform::Collections::Vector<T^>^ vec, int pos1, int pos2)
{
T^ tmp = vec->GetAt(pos1);
vec->SetAt(pos1, vec->GetAt(pos2));
vec->SetAt(pos2,tmp);
}
int compare (T^ c1, T^ c2)
{
int c = wcscmp (c1->Title->Data(),c2->Title->Data());
return -c;
}
int PartitionVec (int left, int right,
Platform::Collections::Vector<T^>^ vec)
{
int i,j;
i = left;
for (int j = left + 1; j <= right; ++j)
{
if (compare (vec->GetAt(j),vec->GetAt(left)) > 0)
{
++i;
swap (vec,i,j);
}
}
swap (vec,left,i);
return i;
}
void QuickSortVec (Platform::Collections::Vector<T^>^ vec,
int start, int end)
{
if (end > start)
{
int pivot_point;
pivot_point = PartitionVec (start, end, vec);
QuickSortVec (vec,start,pivot_point - 1);
QuickSortVec (vec, pivot_point + 1, end);
}
}

greatest common factor on objective c

I'm new to objective c and I would like to know if there is a method for greatest common factor
gcf() for example so you get the idea
There's no out of the box function. Since Objective-C is a superset of C, you can grab an existing library or set of functions and include it where necessary.
Based on http://www.idevelopment.info/data/Programming/data_structures/c/gcd/gcd.c, you might do this:
// gcd.h
int gcd(int m, int n);
// gcd.c
int gcd(int m, int n) {
int t, r;
if (m < n) {
t = m;
m = n;
n = t;
}
r = m % n;
if (r == 0) {
return n;
} else {
return gcd(n, r);
}
}
Include that file whenever you should wish to use the gcd function:
#import "gcd.h"
There is no built in method, but the Euclidean algorithm is easy to implement, and quite efficient.
The binary GCD algorithm can be slightly more efficient. This link has C code implementing it.
By far the most elegant solution I have come across (non-recursive of course):
int gcd (int a, int b){
int c;
while ( a != 0 ) {
c = a; a = b%a; b = c;
}
return b;
}
Source.
Just putting damian86's answer into Objective-C style (reference to self assumes context of an object, modify accordingly, you could make this a category, etc):
-(int)greatestCommonDivisorM:(int)m N:(int)n
{
int t, r;
if (m < n) {
t = m;
m = n;
n = t;
}
r = m % n;
if (r == 0) {
return n;
} else {
return [self greatestCommonDivisorM:n N:r];
}
}