Why are we not using one type of Algorithm to solve problem?

Harsh Garg
2 min readApr 10, 2022

Some set of steps which we used to solve set of steps which we used to solve a problem is termed as algorithm. W can say that these are certain steps which we decide to write before the actual coding.

We can also term it as a Pseudocode i.e. simple language, so that any programmer or non programmer can easily understang the logic behind the code.

These are the characteristics of a good and correct algorithm −

  • Has a set of inputs
  • Steps are uniquely defined
  • Has finite number of steps
  • Produces desired output

Types of Algorithms

  1. Simple recursive algorithms
  2. Backtracking algorithms
  3. Backtracking algorithms
  4. Divide and conquer algorithms
  5. Dynamic programming algorithms
  6. Greedy algorithms
  7. Branch and bound algorithms
  8. Brute force algorithms
  9. Randomized algorithms

Types of Sorting Algorithm

  1. Quick Sort
  2. Merge Sort
  3. Bubble Sort
  4. Insertion Sort
  5. Selection Sort
  6. Heap Sort
  7. Redix Sort
  8. Bucket Sort

Why we are having so many Sort Algorithms when we can use any best of all

The reason we are using different algorithms for different question every question have a different type. Some question can be solve using one type and other using other type. Type of question given we decide the time complexity and space complexity.

For Example

Ques : Given an array of numbers containing n+1 integers where each integer is between 1 and n inclusive. Prove that atleast one duplicate number exist. Assume that there is one duplicated number but can be repeated more then once. Also the linear complexity should be o[1] and you cannot modify the array.

Input : [1,3,4,2,2]

Output: [2]

Solving this question linearly can take more memory

def findDuplicates(nums):
seen = {}
for num in nums:
if num in seen:
return num seen[num] = Trueprint(findDuplicates([1,3,4,2,2]))

Firstly I will try solving it with hashmap but the complexity of that is coming out to be o[n]

Also with approach linear when we compare I and i-1 element complexity is high.

To solve this problem require linear time and constant space so we use Floyd’s Tortois and Hare solution (A simple cycle detection problem where one pointer traverse twice as fast as another and once they meet we can traceback to the point where the cycle begin) since we have value from 1 to n each value point to a index. We have to find that cycle and we have our solution

def findDuplicates(nums):
tortoise = nums[0]
hare = nums[0]
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if tortoise == hare:
break //Floyd hare and tortoise ptr1 = nums[0]
ptr2 = tortoise
while ptr1 != ptr2:
ptr1 = nums[ptr1]
ptr2 = nums[ptr2] return ptr1print(findDuplicates([3,1,3,4,2]))

--

--