Showing posts with label Count. Show all posts
Showing posts with label Count. Show all posts

Wednesday, November 7, 2012

Count number of 1's in a Number

Count the number of 1's in a number's representation.
E.g. Number 23 is 0001 0111
So there are 4 One's

Approach
Left Shift a number (equivalent to dividing by 2). Then if divided number is a double of original number, ignore. Else increment count (the original number is odd).
23 >> 1   gives 11
11 >> 1   gives 5
5  >> 1    gives 2
2 >> 1     gives 1

Solution



Tuesday, October 23, 2012

Sum of elements in unsorted array


 Given an unsorted array.
 With each number, we can associated a sum which is equal to the sum of all the numbers, less than the   current number.
  We've to find the total sum of all those numbers.
  e.g. unsorted array :1, 5, 3, 6, 4.
  for a[0]=1, sum[0]=0
  for a[1]=5, sum[1]=1
  for a[2]=3, sum[2]=1
  for a[3]=6, sum[3]=1+5+3
  for a[4]=4, sum[4]=1+3
  total sum =sum[0]+sum[1]+sum[2]+sum[3]+sum[4] = 15

Solution:
Read each element in the array and put it into a Binary Search Tree. Each node of the BST will hold the value of the element,  and also the sum of the left subtree. As the elements are inserted, calculate the sum of the left subtree. At the end of inserting all the elements, the total sum is calculated



Wednesday, October 17, 2012

Count occurrence of an element in a Sorted Array

Given an array of sorted elements, count the number of times a given element is repeated. The solution cannot be linear.

Solution:- Have given 2 solutions, both are modifications to binary search



UA-36403895-1