How can I prove algorithm correctness ? when i face a problem and come up with a solution the only way to know if this a valid solution or not is by trying some test cases. if they pass through the algorithm and produce the expected output then my algorithm most properly true. but obviously this is not hold all the time because i may forget some corner cases or it is hard to figure out all the test cases. So how can I prove mathematically if my algorithm produce the expected output or not ?
For example, consider the program below.
You’re given a read only array of $n$ integers. Find out if any integer occurs more than $n/3$ times in the array in linear time and constant additional space.
Algorithm: We will use an array of size 3 to count occurrence of numbers let it be count adding numbers to our count array with its proper count. If we reach the size of count array we decrement one from count of each number. If number count becomes zero it can be safely eliminated from the count array.
Here is an example:
- Input: 4 3 3 7 2 3 4 5
- count arr (4,1) 4 as first element and 1 is its count till now
- count arr (4,1)(3,1)
- count arr (4,1)(3,2)
- count arr (4,1)(3,2)(7,1). Here we reach the max allowed size for count then we need to decrement count by one and if it reaches zero its item will be removed from our count array so count arr becomes count arr (3,1). We will proceed with next element in the array which is 2.
- count arr (3,1)(2,1)
- count arr (3,2)(2,1)
- and so on. At the end count arr will be (3,1)(5,1).
We will make another loop to the input array to count occurrence of 3 and 5 and if any one exceeds $n/3$ it will be printed out.