The Wayback Machine - https://web.archive.org/web/20240914151645/https://www.geeksforgeeks.org/what-is-tabu-search/
Open In App

What is TABU Search?

Last Updated : 29 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Tabu search (TS) is an iterative neighborhood search algorithm, where the neighborhood changes dynamically. Tabu search enhances local search by avoiding points in the search space which are already visited. By avoiding already visited points, loops in search space are avoided and local optima can be escaped. 

The main feature of Tabu Search is the use of explicit memory, with two goals: 

  • To prevent the search from revisiting previously visited solutions.
  • To explore the unvisited areas of the solution space. 

How to Optimize an Algorithm Using Tabu Search?

Optimize a solution using the Tabu Search algorithm to find the best solution that minimizes the fitness value of the objective function for a given initial solution, within a specified number of iterations and using a tabu list of limited size.

The code uses Tabu Search to iteratively investigate solutions by assessing their fitness with an objective function and producing nearby solutions with a neighborhood function. Utilizing a tabu list, it attempts to discover the optimal solution with the lowest fitness within a predetermined amount of iterations, avoiding returning to previously explored solutions.

C++
#include <algorithm>
#include <iostream>
#include <numeric> // Added to include accumulate
#include <vector>

// Define the objective function
int objective_function(const std::vector<int>& solution)
{ // Added const qualifier
    // TODO: Implement your objective function here
    // The objective function should evaluate
    // the quality of a given solution and
    // return a numerical value representing
    // the solution's fitness
    // Example: return std::accumulate(solution.begin(),
    // solution.end(), 0);
    return std::accumulate(solution.begin(), solution.end(),
                           0);
}

// Define the neighborhood function
std::vector<std::vector<int> >
get_neighbors(const std::vector<int>& solution)
{ // Added const qualifier
    std::vector<std::vector<int> > neighbors;
    for (size_t i = 0; i < solution.size(); i++) {
        for (size_t j = i + 1; j < solution.size(); j++) {
            std::vector<int> neighbor = solution;
            std::swap(neighbor[i], neighbor[j]);
            neighbors.push_back(neighbor);
        }
    }
    return neighbors;
}

// Define the Tabu Search algorithm
std::vector<int>
tabu_search(const std::vector<int>& initial_solution,
            int max_iterations, int tabu_list_size)
{ // Added const qualifier
    std::vector<int> best_solution = initial_solution;
    std::vector<int> current_solution = initial_solution;
    std::vector<std::vector<int> > tabu_list;

    for (int iter = 0; iter < max_iterations; iter++) {
        std::vector<std::vector<int> > neighbors
            = get_neighbors(current_solution);
        std::vector<int> best_neighbor;
        int best_neighbor_fitness
            = std::numeric_limits<int>::max();

        for (const std::vector<int>& neighbor : neighbors) {
            if (std::find(tabu_list.begin(),
                          tabu_list.end(), neighbor)
                == tabu_list.end()) {
                int neighbor_fitness
                    = objective_function(neighbor);
                if (neighbor_fitness
                    < best_neighbor_fitness) {
                    best_neighbor = neighbor;
                    best_neighbor_fitness
                        = neighbor_fitness;
                }
            }
        }

        if (best_neighbor.empty()) {
            // No non-tabu neighbors found,
            // terminate the search
            break;
        }

        current_solution = best_neighbor;
        tabu_list.push_back(best_neighbor);
        if (tabu_list.size() > tabu_list_size) {
            // Remove the oldest entry from the
            // tabu list if it exceeds the size
            tabu_list.erase(tabu_list.begin());
        }

        if (objective_function(best_neighbor)
            < objective_function(best_solution)) {
            // Update the best solution if the
            // current neighbor is better
            best_solution = best_neighbor;
        }
    }

    return best_solution;
}

int main()
{
    // Example usage
    // Provide an initial solution
    std::vector<int> initial_solution = { 1, 2, 3, 4, 5 };
    int max_iterations = 100;
    int tabu_list_size = 10;

    std::vector<int> best_solution = tabu_search(
        initial_solution, max_iterations, tabu_list_size);
    std::cout << "Best solution:";
    for (int val : best_solution) {
        std::cout << " " << val;
    }
    std::cout << std::endl;
    std::cout << "Best solution fitness: "
              << objective_function(best_solution)
              << std::endl;

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class TabuSearch {
    // Define the objective function
    public static int objectiveFunction(List<Integer> solution) {
        // TODO: Implement your objective function here
        // The objective function should evaluate
        // the quality of a given solution and
        // return a numerical value representing
        // the solution's fitness
        // Example: return solution.stream().mapToInt(Integer::intValue).sum();
        return solution.stream().mapToInt(Integer::intValue).sum();
    }

    // Define the neighborhood function
    public static List<List<Integer>> getNeighbors(List<Integer> solution) {
        List<List<Integer>> neighbors = new ArrayList<>();
        for (int i = 0; i < solution.size(); i++) {
            for (int j = i + 1; j < solution.size(); j++) {
                List<Integer> neighbor = new ArrayList<>(solution);
                // Swap elements at indices i and j
                int temp = neighbor.get(i);
                neighbor.set(i, neighbor.get(j));
                neighbor.set(j, temp);
                neighbors.add(neighbor);
            }
        }
        return neighbors;
    }

    // Define the Tabu Search algorithm
    public static List<Integer> tabuSearch(List<Integer> initialSolution, 
                                           int maxIterations, int tabuListSize) {
        List<Integer> bestSolution = new ArrayList<>(initialSolution);
        List<Integer> currentSolution = new ArrayList<>(initialSolution);
        List<List<Integer>> tabuList = new ArrayList<>();

        for (int iter = 0; iter < maxIterations; iter++) {
            List<List<Integer>> neighbors = getNeighbors(currentSolution);
            List<Integer> bestNeighbor = new ArrayList<>();
            int bestNeighborFitness = Integer.MAX_VALUE;

            for (List<Integer> neighbor : neighbors) {
                if (!tabuList.contains(neighbor)) {
                    int neighborFitness = objectiveFunction(neighbor);
                    if (neighborFitness < bestNeighborFitness) {
                        bestNeighbor = new ArrayList<>(neighbor);
                        bestNeighborFitness = neighborFitness;
                    }
                }
            }

            if (bestNeighbor.isEmpty()) {
                // No non-tabu neighbors found, terminate the search
                break;
            }

            currentSolution = new ArrayList<>(bestNeighbor);
            tabuList.add(bestNeighbor);

            if (tabuList.size() > tabuListSize) {
                // Remove the oldest entry from the tabu list if it exceeds the size
                tabuList.remove(0);
            }

            if (objectiveFunction(bestNeighbor) < objectiveFunction(bestSolution)) {
                // Update the best solution if the current neighbor is better
                bestSolution = new ArrayList<>(bestNeighbor);
            }
        }

        return bestSolution;
    }

    public static void main(String[] args) {
        // Example usage
        // Provide an initial solution
        List<Integer> initialSolution = List.of(1, 2, 3, 4, 5);
        int maxIterations = 100;
        int tabuListSize = 10;

        List<Integer> bestSolution = 
          tabuSearch(initialSolution, maxIterations, tabuListSize);
        System.out.print("Best solution:");
        for (int val : bestSolution) {
            System.out.print(" " + val);
        }
        System.out.println();
        System.out.println("Best solution fitness: " + objectiveFunction(bestSolution));
    }
}
Python
import random

# Define the objective function


def objective_function(solution):
    # TODO: Implement your objective function here
    # The objective function should evaluate
    # the quality of a given solution and
    # return a numerical value representing
    # the solution's fitness
    # Example: return sum(solution)
    return sum(solution)

# Define the neighborhood function


def get_neighbors(solution):

    # TODO: Implement your neighborhood function here
    # The neighborhood function should generate
    # a set of neighboring solutions based on a given solution
    # Example: Generate neighboring solutions by
    # swapping two elements in the solution

    neighbors = []
    for i in range(len(solution)):
        for j in range(i + 1, len(solution)):
            neighbor = solution[:]
            neighbor[i], neighbor[j] = neighbor[j], neighbor[i]
            neighbors.append(neighbor)
    return neighbors

# Define the Tabu Search algorithm


def tabu_search(initial_solution, max_iterations, tabu_list_size):
    best_solution = initial_solution
    current_solution = initial_solution
    tabu_list = []

    for _ in range(max_iterations):
        neighbors = get_neighbors(current_solution)
        best_neighbor = None
        best_neighbor_fitness = float('inf')

        for neighbor in neighbors:
            if neighbor not in tabu_list:
                neighbor_fitness = objective_function(neighbor)
                if neighbor_fitness &lt; best_neighbor_fitness:
                    best_neighbor = neighbor
                    best_neighbor_fitness = neighbor_fitness

        if best_neighbor is None:

            # No non-tabu neighbors found,
            # terminate the search
            break

        current_solution = best_neighbor
        tabu_list.append(best_neighbor)
        if len(tabu_list) &gt; tabu_list_size:

            # Remove the oldest entry from the
            # tabu list if it exceeds the size
            tabu_list.pop(0)

        if objective_function(best_neighbor) &lt; objective_function(best_solution):
            # Update the best solution if the
            # current neighbor is better
            best_solution = best_neighbor

    return best_solution


# Example usage
# Provide an initial solution
initial_solution = [1, 2, 3, 4, 5]
max_iterations = 100
tabu_list_size = 10

best_solution = tabu_search(initial_solution, max_iterations, tabu_list_size)
print(&quot;Best solution: {}&quot;.format(best_solution))
print(&quot;Best solution fitness: {}&quot;.format(objective_function(best_solution)))
C#
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
      // Define the objective function
    static int ObjectiveFunction(List<int> solution)
    {
     // Added const qualifier
    // TODO: Implement your objective function here
    // The objective function should evaluate
    // the quality of a given solution and
    // return a numerical value representing
    // the solution's fitness
    // Example: return std::accumulate(solution.begin(),
    // solution.end(), 0);
        return solution.Sum();
    }

      // Define the neighborhood function
    static List<List<int>> GetNeighbors(List<int> solution)
    {
          // Added const qualifier
        List<List<int>> neighbors = new List<List<int>>();
        for (int i = 0; i < solution.Count; i++)
        {
            for (int j = i + 1; j < solution.Count; j++)
            {
                List<int> neighbor = new List<int>(solution);
                neighbor[i] = solution[j];
                neighbor[j] = solution[i];
                neighbors.Add(neighbor);
            }
        }
        return neighbors;
    }

      // Define the Tabu Search algorithm
    static List<int> TabuSearch(List<int> initial_solution, 
                                int max_iterations, 
                                int tabu_list_size)
            {
      
    // Added const qualifier
    List<int> best_solution = initial_solution;
    List<int> current_solution = initial_solution;
    List<List<int>> tabu_list = new List<List<int>>();
    for (int iter = 0; iter < max_iterations; iter++)
    {
        List<List<int>> neighbors = GetNeighbors(current_solution);
        List<int> best_neighbor = new List<int>();
        int best_neighbor_fitness = int.MaxValue;
        foreach (List<int> neighbor in neighbors)
        {
            if (!tabu_list.Contains(neighbor))
            {
                int neighbor_fitness = ObjectiveFunction(neighbor);
                if (neighbor_fitness < best_neighbor_fitness)
                {
                    best_neighbor = neighbor;
                    best_neighbor_fitness = neighbor_fitness;
                }
            }
        }
        if (best_neighbor.Count == 0)
        {
              // No non-tabu neighbors found,
            // terminate the search
            break;
        }
        current_solution = best_neighbor;
        tabu_list.Add(best_neighbor);
        if (tabu_list.Count > tabu_list_size)
        {
              // Remove the oldest entry from the
            // tabu list if it exceeds the size
            tabu_list.RemoveAt(0);
        }
        if (ObjectiveFunction(best_neighbor) < ObjectiveFunction(best_solution))
        {
              // Update the best solution if the
            // current neighbor is better
            best_solution = best_neighbor;
        }
    }
    return best_solution;
}
      static void Main()
    {
          // Example usage
        // Provide an initial solution
        List<int> initial_solution = new List<int> { 1, 2, 3, 4, 5 };
        int max_iterations = 100;
        int tabu_list_size = 10;
        List<int> best_solution = TabuSearch(
            initial_solution, max_iterations, tabu_list_size);
        Console.Write("Best solution:");
        foreach (int val in best_solution)
        {
            Console.Write(" " + val);
        }
        Console.WriteLine();
        Console.WriteLine("Best solution fitness: " +
            ObjectiveFunction(best_solution));
    }

}
JavaScript
function objectiveFunction(solution) {
    // TODO: Implement your objective function here
    // The objective function should evaluate
    // the quality of a given solution and
    // return a numerical value representing
    // the solution's fitness
    // Example: return solution.reduce((sum, val) => sum + val, 0);
    return solution.reduce((sum, val) => sum + val, 0);
}

function getNeighbors(solution) {
    const neighbors = [];
    for (let i = 0; i < solution.length; i++) {
        for (let j = i + 1; j < solution.length; j++) {
            const neighbor = [...solution];
            // Swap elements at indices i and j
            [neighbor[i], neighbor[j]] = [neighbor[j], neighbor[i]];
            neighbors.push(neighbor);
        }
    }
    return neighbors;
}

function tabuSearch(initialSolution, maxIterations, tabuListSize) {
    let bestSolution = [...initialSolution];
    let currentSolution = [...initialSolution];
    const tabuList = [];

    for (let iter = 0; iter < maxIterations; iter++) {
        const neighbors = getNeighbors(currentSolution);
        let bestNeighbor = [];
        let bestNeighborFitness = Number.MAX_VALUE;

        for (const neighbor of neighbors) {
            if (!tabuList.some(entry => JSON.stringify(entry) === JSON.stringify(neighbor))) {
                const neighborFitness = objectiveFunction(neighbor);
                if (neighborFitness < bestNeighborFitness) {
                    bestNeighbor = [...neighbor];
                    bestNeighborFitness = neighborFitness;
                }
            }
        }

        if (bestNeighbor.length === 0) {
            // No non-tabu neighbors found, terminate the search
            break;
        }

        currentSolution = [...bestNeighbor];
        tabuList.push([...bestNeighbor]);

        if (tabuList.length > tabuListSize) {
            // Remove the oldest entry from the tabu list if it exceeds the size
            tabuList.shift();
        }

        if (objectiveFunction(bestNeighbor) < objectiveFunction(bestSolution)) {
            // Update the best solution if the current neighbor is better
            bestSolution = [...bestNeighbor];
        }
    }

    return bestSolution;
}

// Example usage
const initialSolution = [1, 2, 3, 4, 5];
const maxIterations = 100;
const tabuListSize = 10;

const bestSolution = tabuSearch(initialSolution, maxIterations, tabuListSize);
console.log("Best solution:", bestSolution.join(" "));
console.log("Best solution fitness:", objectiveFunction(bestSolution));

Output
Best solution: 1 2 3 4 5
Best solution fitness: 15

NOTE:  We can replace the objective_function implementation with your specific objective function and provide a suitable initial_solution to ensure the code works as intended.

Explanation of code:

  • Implementing the objective function and the neighborhood function unique to your situation is required by the code.
  • A solution’s fitness is quantified numerically by the objective function, which assesses a solution’s quality.
  • Using a given solution as a starting point, the neighborhood function creates neighboring solutions.
  • The best non-tabu neighbor is considered as the search space is iteratively explored using the Tabu Search algorithm.
  • According to the specifications of your problem, you should adjust the starting solution, maximum iterations, and tabu list size.
  • Depending on how difficult your problem is, the code provides a basic framework for implementing Tabu Search and might need more customization.
  • Don’t forget to replace the TODO placeholder sections with your actual implementation for your particular problem, describing the solution representation and fitness calculation in the objective function.

Complexity Analysis: 

As Tabu Search’s temporal complexity varies depending on the particular problem being solved and the scope of the search area, there is no universal method for calculating it. 

  • The worst-case time complexity of a Tabu Search problem, which is commonly expressed as O(2^n), where n is the size of the search space, nevertheless, can be exponential in the magnitude of the problem.
  • Although it depends on the size of the search space, Tabu Search’s space complexity is often substantially less than its worst-case time complexity. The size of the search space is denoted as O(k*n), where n is the size of the search space and k is the size of the Tabu List or the number of candidate solutions being assessed and stored in memory.

It’s important to keep in mind that the actual time and space complexity of Tabu Search might vary significantly depending on the particular problem being solved, the algorithm parameters chosen (such as the size of the Tabu List, the aspiration criteria, the diversification strategies, etc.), and the effectiveness of the implementation. To discover the greatest performance for a particular task, it is therefore frequently required to experiment with various parameter values and implementation methodologies.

Examples of Problems to Solve with Tabu Search:

  • N-Queens Problem
  • Traveling Salesman Problem (TSP)
  • Minimum Spanning Tree (MST)
  • Assignment Problems
  • Vehicle Routing
  • DNA Sequencing

Advantages of Tabu Search:

  • Can be applied to both discrete and continuous solutions.
  • The tabu list can be used to resist cycles and revert to old solutions.

Disadvantages of Tabu Search:

  • High Number of Iterations
  • Presence of tune-able parameters


Previous Article
Next Article

Similar Reads

Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Breadth-first Search is a special case of Uniform-cost search
In AI there are mainly two types of search techniques: Un-informed/blind search techniquesInformed search techniques Search algorithms under the Uninformed category are: Breadth-first searchUniform cost searchDepth-first searchDepth limited searchIterative deepening depth-first searchBidirectional search Search algorithms under the Informed categor
6 min read
Anagram Substring Search (Or Search for all permutations) | Set 2
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Examples: Input: txt[] = "BACDGABCDA" pat[] = "ABCD"Output: Found at Index 0 Found at Index 5 Found at Index 6 Input: txt[] = "AAABABAA" p
10 min read
Difference between Best-First Search and A* Search?
Best-First Search: Best-First search is a searching algorithm used to find the shortest path which uses distance as a heuristic. The distance between the starting node and the goal node is taken as heuristics. It defines the evaluation function for each node n in the graph as f(n) = h(n) where h(n) is heuristics function. A*Search: A*search is a se
2 min read
Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to a traditional line
9 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
15 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include &lt;bits/stdc++.h&gt; using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
Sublist Search (Search a linked list in another list)
Given two linked lists, the task is to check whether the first list is present in 2nd list or not. Examples: Input: list1 = 10-&gt;20 list2 = 5-&gt;10-&gt;20 Output : LIST FOUNDInput: list1 = 1-&gt;2-&gt;3-&gt;4 list2 = 1-&gt;2-&gt;1-&gt;2-&gt;3-&gt;4 Output: LIST FOUNDInput: list1 = 1-&gt;2-&gt;3-&gt;4 list2 = 1-&gt;2-&gt;2-&gt;1-&gt;2-&gt;3 Outpu
15+ min read
Best First Search (Informed Search)
In BFS and DFS, when we are at a node, we can consider any of the adjacent as the next node. So both BFS and DFS blindly explore paths without considering any cost function.  The idea of Best First Search is to use an evaluation function to decide which adjacent is most promising and then explore. Best First Search falls under the category of Heuri
9 min read
Repeatedly search an element by doubling it after every successful search
Given an array "a[]" and integer "b". Find whether b is present in a[] or not. If present, then double the value of b and search again. We repeat these steps until b is not found. Finally we return value of b. Examples: Input : a[] = {1, 2, 3} b = 1 Output :4 Initially we start with b = 1. Since it is present in array, it becomes 2. Now 2 is also p
6 min read
What is the difference between Binary Search and Jump Search?
Binary Search and Jump Search are two popular algorithms used for searching elements in a sorted array. Although they both try to identify a target value as quickly as possible, they use distinct approaches to get there. In this article, we will discuss the difference between binary search and jump search. Let's explore how these algorithms optimiz
2 min read
Is ternary search faster than binary search?
Binary search is a widely used algorithm for searching a sorted array. It works by repeatedly dividing the search space in half until the target element is found. Ternary search is a variation of binary search that divides the search space into three parts instead of two. This article explores the performance comparison between ternary search and b
3 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Is there any search faster than Binary Search?
No, there is no search faster than Binary Search. Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc. How Does Binary Search Work?Bin
3 min read
Difference Between Linear Search and Jump Search
Linear Search and Jump Search are two different techniques used to find an element in a list. Each algorithm has its own set of characteristics, advantages, and limitations, making them suitable for different scenarios. This article explores the key differences between Linear Search and Jump Search. What is Linear Search?Linear Search, also known a
3 min read
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first
10 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes positive for the first time. Since f() is monotonic
11 min read
How to handle duplicates in Binary Search Tree?
In a Binary Search Tree (BST), all keys in left subtree of a key must be smaller and all keys in right subtree must be greater. So a Binary Search Tree by definition has distinct keys. How to allow duplicates where every insertion inserts one more key with a value and every deletion deletes one occurrence?A Simple Solution is to allow same keys on
15+ min read
How to implement decrease key or change key in Binary Search Tree?
Given a Binary Search Tree, write a function that takes the following three as arguments: Root of tree Old key value New Key Value The function should change old key value to new key value. The function may assume that old key-value always exists in Binary Search Tree. Example: Input: Root of below tree 50 / \ 30 70 / \ / \ 20 40 60 80 Old key valu
15+ min read
Iterative Search for a key 'x' in Binary Tree
Given a Binary Tree and a key to be searched in it, write an iterative method that returns true if key is present in Binary Tree, else false. For example, in the following tree, if the searched key is 3, then function should return true and if the searched key is 12, then function should return false. One thing is sure that we need to traverse comp
14 min read
Data Structures | Binary Search Trees | Question 1
What is the worst case time complexity for search, insert and delete operations in a general Binary Search Tree for a skewed tree ? (A) O(n) for all (B) O(Logn) for all (C) O(Logn) for search and insert, and O(n) for delete (D) O(Logn) for search, and O(n) for insert and delete Answer: (A)Explanation: In skewed Binary Search Tree (BST), all three o
1 min read
Data Structures | Binary Search Trees | Question 2
In delete operation of BST, we need inorder successor (or predecessor) of a node when the node to be deleted has both left and right child as non-empty. Which of the following is true about inorder successor needed in delete operation? (A) Inorder Successor is always a leaf node (B) Inorder successor is always either a leaf node or a node with empt
2 min read
Data Structures | Balanced Binary Search Trees | Question 2
The worst case running time to search for an element in a balanced in a binary search tree with n2^n elements is (A) [Tex]\\Theta(n log n) [/Tex](B) [Tex]\\Theta (n2^n) [/Tex](C) [Tex]\\Theta (n) [/Tex](D) [Tex]\\Theta (log n) [/Tex] (A) A (B) B (C) C (D) D Answer: (C)Explanation: Time taken to search an element is [Tex]\\Theta (h) [/Tex]where h is
1 min read
Data Structures | Binary Search Trees | Question 4
How many distinct binary search trees can be created out of 4 distinct keys? (A) 4 (B) 14 (C) 24 (D) 42 Answer: (B) Explanation: number of distinct BSTs = (2n)!/[(n+1)!*n!] . Quiz of this Question Please comment below if you find anything wrong in the above post
1 min read
Data Structures | Binary Search Trees | Question 5
Which of the following traversal outputs the data in sorted order in a BST? (A) Preorder (B) Inorder (C) Postorder (D) Level order Answer: (B)Explanation: Inorder traversal of a BST outputs data in sorted order. Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read