Skip to content
    geeksforgeeks
    • Interview Prep
      • DSA
      • Interview Corner
      • Aptitude & Reasoning
      • Practice Coding Problems
      • All Courses
    • Tutorials
      • Python
      • Java
      • ML & Data Science
      • Programming Languages
      • Web Development
      • CS Subjects
      • DevOps
      • Software and Tools
      • School Learning
    • Tracks
      • Languages
        • Python
        • C
        • C++
        • Java
        • Advanced Java
        • SQL
        • JavaScript
        • C#
      • Interview Preparation
        • GfG 160
        • GfG 360
        • System Design
        • Core Subjects
        • Interview Questions
        • Interview Puzzles
        • Aptitude and Reasoning
        • Product Management
        • Computer Organisation and Architecture
      • Data Science
        • Python
        • Data Analytics
        • Complete Data Science
        • Gen AI
        • Agentic AI
      • Dev Skills
        • Full-Stack Web Dev
        • DevOps
        • Software Testing
        • CyberSecurity
        • NextJS
        • Git
      • Tools
        • Computer Fundamentals
        • AI Tools
        • MS Excel & Google Sheets
        • MS Word & Google Docs
      • Maths
        • Maths For Computer Science
        • Engineering Mathematics
        • School Maths
    • Python Tutorial
    • Data Types
    • Interview Questions
    • Examples
    • Quizzes
    • DSA Python
    • Data Science
    • NumPy
    • Pandas
    • Practice
    • Django
    • Flask
    • Projects
    Open In App

    Python DSA Libraries

    Last Updated : 23 Jul, 2025
    Comments
    Improve
    Suggest changes
    3 Likes
    Like
    Report

    Data Structures and Algorithms (DSA) serve as the backbone for efficient problem-solving and software development. Python, known for its simplicity and versatility, offers a plethora of libraries and packages that facilitate the implementation of various DSA concepts. In this article, we'll delve into some essential Python libraries for DSA, covering arrays, linked lists, queues, hash maps, heaps, trees, and specialized algorithms like Bisect, Interval Trees, and Trie Trees.

    Table of Content

    • Array in Python
    • Linked list in Python
    • Queue in Python
    • Hash Map in Python
    • Heap in Python
    • Tree in Python
    • Bisect Algorithm in Python
    • Interval Tree in Python
    • Trie Tree in Python

    Package or Library to Implement Array in Python

    Array in Python can be created by importing an array module. array(data_type, value_list) is used to create an array with data type and value list specified in its arguments. 

    Package or Library to implement Array in Python

    The 'array library' in Python is used to implement Arrays in Python

    What is an 'array module' in Python?

    An array module in Python defines an object type that can compactly represent an array of basic values: characters, integers, and floating-point numbers.

    Important Methods in Array library

    • array.itemsize()
    • array.buffer_info()
    • array.count(x)
    • array.extend(iterable)

    Syntax to use Array Library in Python:

    # Importing array module
    import array as <module variable>
    # Creating an array in Python using Array Module
    <array variable> = <module variable>.array('<data type of elements>', <list of elements of specified type>)

    Example to use Array Library in Python

    Python
    import array
    
    # Create an array of integers
    int_array = array.array('i', [1, 2, 3, 4, 5])
    
    # Access elements
    print(int_array[0])
    

    Output
    1

    Package or Library to Implement Linked list in Python

    Linked List consists of a sequence of elements called nodes, where each node contains some data and a reference (or pointer) to the next node in the sequence. The last node typically points to null to indicate the end of the list.

    Package or Library to implement Array in Python

    The 'collections.deque library' in Python is used to implement Linked list in Python.

    What is 'deque module' in Python?

    In Python, the collections module provides a versatile deque class, which stands for "double-ended queue". Although it's not specifically named as a "double linked list", it internally uses a doubly linked list structure to provide efficient insertion and deletion operations at both ends of the queue.

    Important Methods in deque library

    • append(ele): Add ele to the right side of the deque
    • appendleft(ele): Add ele to the left side of the deque.
    • clear():Remove all elements from the deque leaving it with length 0.
    • copy(): Create a shallow copy of the deque.
    • count(ele): Count the number of deque elements equal to x.
    • extend(): Extend the right side of the deque by appending elements from the iterable argument.
    • extendleft(): Extend the left side of the deque by appending elements from iterable.
    • index(): Return the position of x in the deque. Returns the first match.
    • insert(): Insert x into the deque at position i.
    • pop(): Remove and return an element from the right side of the deque.
    • popleft(): Remove and return an element from the left side of the deque.
    • remove(): Remove the first occurrence of value.
    • reverse(): Reverse the elements of the deque.
    • rotate(): Rotate the deque n steps to the right.

    Example to use Deque Library in Python

    Python
    from collections import deque
    
    # Creating a deque
    my_queue = deque()
    
    # Adding elements to the queue
    my_queue.append(1)    # Adds to the right end
    my_queue.appendleft(2) # Adds to the left end
    
    # Removing elements from the queue
    element = my_queue.pop()    # Removes and returns from the right end
    element = my_queue.popleft() # Removes and returns from the left end
    
    # Other methods available in deque include: extend, extendleft, rotate, etc.
    

    Package or Library to Implement Queue in Python

    In a queue, elements are added (enqueue operation) to the rear (also called the "tail") and removed (dequeue operation) from the front (also called the "head"). This ensures that the oldest elements are processed first, while newer elements are added to the end of the queue.

    Package or Library to Implement Hash Map in Python

    The 'queue.Queue library' in Python is used to implement Queue in Python.

    What is 'Queue module' in Python?

    In Python, the queue module provides various classes that implement multi-producer, multi-consumer queues. These classes are designed for use in multi-threaded programming and are especially useful for communication between threads safely.

    Important Methods in Counter library

    • Queue.qsize(): Return the approximate size of the queue.
    • Queue.empty(): Return True if the queue is empty, False otherwise.
    • Queue.full(): Return True if the queue is full, False otherwise.
    • Queue.put(): Put item into the queue.
    • Queue.get(): Remove and return an item from the queue.

    Example to use Queue Library in Python

    Python
    from queue import Queue
    
    # Creating a queue
    my_queue = Queue()
    
    # Adding elements to the queue
    my_queue.put(1)
    my_queue.put(2)
    my_queue.put(3)
    
    # Removing elements from the queue
    # Removes and returns the first element added (FIFO)
    element = my_queue.get()  
    print(element) 
    
    # Checking if the queue is empty
    print(my_queue.empty())  
    
    # Getting the size of the queue
    print(my_queue.qsize())  
    
    # Other methods available in Queue include: empty,
    # qsize, full, task_done, join, etc.
    

    Output

    1
    False
    2

    Package or Library to Implement Hash Map in Python

    A hash map, also known as a hash table, is a data structure that stores key-value pairs. It provides efficient insertion, deletion, and lookup operations. Hash maps work by using a hash function to map keys to indices in an array.

    Package or Library to implement Hash Map in Python

    The 'collections.Counter library' in Python is used to implement Hash Map in Python.

    What is 'Counter Module' in Python?

    A Counter in Python's collections module is a specialized dictionary designed for counting hashable objects. It's particularly useful for counting the occurrences of elements in a collection (e.g., a list or a string). The Counter class provides methods for counting elements efficiently and performing operations like addition, subtraction, intersection, and union of counts.

    Important Methods in Counter Library

    Certainly! Here are some of the key methods provided by Counter objects in Python's collections module, along with explanations for each:

    1. Counter.elements(): Returns an iterator over elements repeating each as many times as its count. The elements are returned in arbitrary order.
    2. Counter.most_common([n]): Returns a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, returns all elements in the counter.
    3. Counter.subtract([iterable-or-mapping]): Elements are subtracted from an iterable or from another mapping (or counter).
    4. Counter.total(): Compute the sum of the counts.
    5. Counter.update([iterable-or-mapping]): Elements are counted from an iterable or added-in from another mapping (or counter).
    6. Counter.fromkeys(iterable, value): Class method that creates a new Counter object from an iterable and initializes each element's count to the specified value.

    Example to use Counter Library in Python

    Python
    from collections import Counter
    
    # Create a Counter object from a list
    my_list = ['apple', 'banana', 'apple', 'orange', 'apple', 'banana']
    my_counter = Counter(my_list)
    
    print(my_counter)
    

    Output

    Counter({'apple': 3, 'banana': 2, 'orange': 1})

    Efficient Libraries for Managing Dictionaries

    Also there are collections.ChainMap, collections.defaultdict, and collections.OrderedDict Method inside the collection Library. Here, The Counter itself doesn't inherently utilize it, but you might use them together in certain scenarios, depending on your specific requirements.

    What is 'ChainMap Library' in Python?

    A ChainMap is a class in Python's collections module that provides the ability to link multiple mappings together to create a single view. It allows you to search multiple dictionaries as if they were one.

    # Python program to demonstrate ChainMap 
    from collections import ChainMap

    d1 = {'a': 1, 'b': 2}
    d2 = {'c': 3, 'd': 4}
    d3 = {'e': 5, 'f': 6}

    # Defining the chainmap
    c = ChainMap(d1, d2, d3)

    What is 'defaultdict Library' in Python?

    The defaultdict is another handy class provided by the collections module in Python. It's a subclass of the built-in dict class and provides a convenient way to create dictionaries with default values for keys that haven't been explicitly set.

    from collections import defaultdict
    # Define a defaultdict with default value 0
    my_defaultdict = defaultdict(int)

    What is 'OrderedDict Library' in Python?

    The OrderedDict is a dictionary subclass provided by the collections module in Python. It's similar to the built-in dict class but with one key difference: it maintains the order of insertion of its keys.

    from collections import OrderedDict
    my_ordered_dict = OrderedDict()

    Package or Library to Implement Heap in Python

    A heap is a specialized tree-based data structure that satisfies the heap property. Heaps are commonly implemented as binary trees, specifically binary min-heaps or binary max-heaps.

    Package or Library to Implement Hash Map in Python

    The 'heapq library' in Python is used to implement Queue in Python.

    What is 'heapq module' in Python?

    The heapq module in Python provides a collection of heap-based algorithms, specifically functions to implement heaps as regular lists and perform heap operations efficiently. Despite being named "heapq", it doesn't provide a separate heap data structure class. Instead, it offers functions to manipulate regular Python lists as heaps.

    Important Methods in Counter library

    The heapq module in Python provides functions rather than methods for heap operations. Here are the main functions available in the heapq module:

    • heapify(heap): This function transforms a list into a heap in linear time.
    • heappush(heap, item): This function adds the item to the heap while maintaining the heap property. It inserts the item at the appropriate position within the heap.
    • heappop(heap): This function removes and returns the smallest element from the heap.
    • heappushpop(heap, item): It pushes the item onto the heap and then pops and returns the smallest element from the heap.
    • heapreplace(heap, item): This function first pops and returns the smallest element from the heap before pushing the new item onto the heap.
    • merge(iterables): This function merges multiple sorted inputs (iterables) into a single sorted output (an iterator).
    • nlargest(n, iterable): This function returns the n largest elements from the iterable, sorted in descending order.
    • nsmallest(n, iterable): This function returns the n smallest elements from the iterable, sorted in ascending order.

    Example to use Heapq Library in Python

    Python
    # importing &quot;heapq&quot; to implement heap queue
    import heapq
    
    # initializing list
    li = [5, 7, 9, 1, 3]
    
    # using heapify to convert list into heap
    heapq.heapify(li)
    
    # printing created heap
    print (&quot;The created heap is : &quot;,(list(li)))
    

    Output

    The created heap is :  [1, 3, 9, 7, 5]

    Package to Implement Tree in Python

    A tree is a hierarchical data structure consisting of nodes connected by edges. It's a widely used data structure in computer science for organizing data in a hierarchical manner.

    Package or Library to Implement Tree in Python

    The 'treelib library' in Python is used to implement Queue in Python.

    What is 'treelib Module' in Python?

    The treelib is a Python library that provides functionality for working with tree structures. It allows you to create, manipulate, traverse, and visualize tree data structures efficiently.

    Important Methods in bisect library

    • create_node(tag, node_id=None, parent=None): Creates a new node with the specified tag and optional data. Optionally specifies the node identifier (node_id) and parent node (parent).
    • remove_node(node_id): Removes the node with the specified identifier from the tree.
    • get_node(node_id): Retrieves the node with the specified identifier from the tree.
    • update_node(node_id, tag=None, data=None): Updates the tag and/or data of the node with the specified identifier.
    • contains(node_id): Checks if the tree contains a node with the specified identifier.
    • parent(node_id): Returns the parent node identifier of the node with the specified identifier.
    • children(node_id): Returns a list of identifiers of the children nodes of the node with the specified identifier.
    • depth(node_id): Calculates the depth of the node with the specified identifier in the tree.
    • size(node_id=None): Calculates the size (number of nodes) of the subtree rooted at the node with the specified identifier. If no identifier is provided, calculates the size of the entire tree.
    • height(node_id=None): Calculates the height (maximum depth) of the subtree rooted at the node with the specified identifier. If no identifier is provided, calculates the height of the entire tree.
    • show(line_type="ascii"): Prints a textual representation of the tree

    Example to use Bisect Library in Python

    Python
    from treelib import Node, Tree
    
    # Create a new binary tree
    tree = Tree()
    
    # Add nodes to the tree
    tree.create_node(&quot;Root&quot;, &quot;root&quot;)  # Create the root node
    # Create a left child node
    tree.create_node(&quot;Left Child&quot;, &quot;left&quot;, parent=&quot;root&quot;)  
    # Create a right child node
    tree.create_node(&quot;Right Child&quot;, &quot;right&quot;, parent=&quot;root&quot;)  
    
    # Add more nodes to the left child
     # Create a left grandchild node
    tree.create_node(&quot;Left Grandchild&quot;, &quot;left_grand&quot;, parent=&quot;left&quot;) 
    # Create a right grandchild node
    tree.create_node(&quot;Right Grandchild&quot;, &quot;right_grand&quot;, parent=&quot;left&quot;)  
    
    # Print the tree structure
    print(&quot;Tree structure:&quot;)
    tree.show()
    
    # Traverse the tree (pre-order traversal)
    print(&quot;\nPre-order traversal:&quot;)
    for node in tree.all_nodes():
        print(node.tag)
    
    # Visualize the tree
    tree.show(line_type=&quot;ascii-em&quot;)
    
    # Visualize the tree using Graphviz (requires Graphviz installed)
    # tree.show()
    

    Output

    Tree structure:
    root
    ├── left
    │ ├── left_grand
    │ └── right_grand
    └── right
    Pre-order traversal:
    root
    left
    left_grand
    right_grand
    right
    root
    |-- left
    | |-- left_grand
    | +-- right_grand
    +-- right

    Library to Implement Bisect Algorithm in Python

    The bisect algorithm, also known as binary search, is a technique used to efficiently find the position where an element should be inserted into a sorted list to maintain the sorted order. It's named after the bisect function provided by the bisect module in Python, which implements this algorithm.

    Package or Library to Implement Bisect Algorithm in Python

    The 'bisect library' in Python is used to implement Queue in Python.

    What is 'bisect Module' in Python?

    The bisect module in Python provides functions to efficiently insert elements into sorted lists and find insertion points for new elements while maintaining the sorted order. It's particularly useful when dealing with sorted collections and needing to maintain their order efficiently.

    Important Methods in bisect library

    As bisect module support additional methods, Please mention all the methods in points with there explanation

    • bisect(list, num, beg, end): This function returns the position in the sorted list.
    • bisect.bisect_left()
    • bisect.bisect_right()
    • bisect.insort_left()
    • bisect.insort_right()
    • bisect.insort()

    Example to use Bisect Library in Python

    Python
    import bisect
    
    # Sorted list
    sorted_list = [1, 3, 5, 7, 9]
    
    # Element to insert
    new_element = 6
    
    # Find the insertion point using bisect_left
    insertion_point = bisect.bisect_left(sorted_list, new_element)
    
    # Insert the element into the sorted list
    sorted_list.insert(insertion_point, new_element)
    
    print(&quot;Sorted list after insertion:&quot;, sorted_list)
    print(&quot;New element inserted at index:&quot;, insertion_point)
    

    Output

    Sorted list after insertion: [1, 3, 5, 6, 7, 9]
    New element inserted at index: 3

    Package to Implement Interval Tree in Python

    An interval tree is a data structure used for efficiently storing and querying intervals or ranges. It's a type of binary search tree specifically designed to handle interval queries effectively.

    Package or Library to Implement Bisect Algorithm in Python

    The 'intervaltree library' in Python is used to implement Queue in Python.

    What is 'intervaltree Module' in Python?

    The intervaltree library in Python is a data structure designed to efficiently store and query intervals or ranges. It provides an implementation of an interval tree, a type of binary search tree optimized for interval queries.

    Important Methods in intervaltree library

    The intervaltree module in Python provides several methods for efficiently working with interval trees.

    • add(interval): Adds an interval to the interval tree.
    • remove(interval): Removes an interval from the interval tree.
    • search(begin): Searches for intervals that overlap with the given range defined by begin and end (inclusive).
    • overlap(begin): Alias for search(). Searches for intervals that overlap with the given range defined by begin and end.
    • at(begin): Searches for intervals that contain the specified point begin. Returns a set of intervals that contain the point.
    • clear(): Clears all intervals from the interval tree, making it empty.
    • copy(): Creates a shallow copy of the interval tree, including all intervals.
    • discard(interval): Removes an interval from the interval tree if it exists, similar to the remove() method.
    • items(): Returns a generator that yields all intervals stored in the interval tree.
    • size(): Returns the number of intervals stored in the interval tree.
    • empty(): Returns True if the interval tree is empty, False otherwise.

    Example to use Intervaltree Library in Python

    Python
    from intervaltree import IntervalTree, Interval
    
    # Create an interval tree
    tree = IntervalTree()
    
    # Add intervals to the tree
    tree.add(Interval(1, 5))
    tree.add(Interval(3, 8))
    tree.add(Interval(6, 10))
    tree.add(Interval(12, 15))
    
    # Query intervals that overlap with a given range
    query_range = (4, 7)
    result_intervals = tree.search(*query_range)
    
    print(&quot;Intervals that overlap with the query range:&quot;, result_intervals)
    
    # Iterate over the result intervals and print their start and end points
    print(&quot;Start and end points of the overlapping intervals:&quot;)
    for interval in result_intervals:
        print(&quot;Start:&quot;, interval.begin, &quot;End:&quot;, interval.end)
    

    Output

    Intervals that overlap with the query range: {Interval(1, 5), Interval(3, 8), Interval(6, 10)}
    Start and end points of the overlapping intervals:
    Start: 1 End: 5
    Start: 3 End: 8
    Start: 6 End: 10

    Package to Implement Trie Tree in Python

    A Trie, also known as a prefix tree or digital tree, is a tree-like data structure used to store a dynamic set of strings where the keys are usually strings. Each node in a Trie represents a single character of a string, and the path from the root to a particular node represents a prefix of one or more strings.

    Package or Library to Implement Trie in Python

    The 'trie library' in Python is used to implement Queue in Python.

    What is 'intervaltree Module' in Python?

    The intervaltree library in Python is a data structure designed to efficiently store and query intervals or ranges. It provides an implementation of an interval tree, a type of binary search tree optimized for interval queries.

    Important Methods in intervaltree library

    • Trie(): Constructor method to create a new Trie object.
    • insert(str) -> None: Inserts a word into the trie.
    • search(str): Searches for a word in the trie. Returns True if the word is found, otherwise False.
    • startswith(prefix: str): Checks if any word in the trie starts with the given prefix. Returns True if a word starts with the prefix, otherwise False.
    • delete(word: str): Deletes a word from the trie.
    • words(prefix: str = ''): Returns a list .of words in the trie that start with the given prefix.

    Example to use Trie Library in Python

    Python
    from trie import Trie
    
    # Create a new Trie object
    trie = Trie()
    
    # Insert some words into the trie
    trie.insert(&quot;apple&quot;)
    trie.insert(&quot;banana&quot;)
    trie.insert(&quot;app&quot;)
    trie.insert(&quot;bat&quot;)
    trie.insert(&quot;ball&quot;)
    
    # Search for words in the trie
    print(&quot;Search Results:&quot;)
    print(&quot;Does 'apple' exist?&quot;, trie.search(&quot;apple&quot;))  # Output: True
    print(&quot;Does 'app' exist?&quot;, trie.search(&quot;app&quot;))      # Output: True
    print(&quot;Does 'orange' exist?&quot;, trie.search(&quot;orange&quot;))  # Output: False
    
    # Check if any word starts with a given prefix
    print(&quot;\nStartsWith Results:&quot;)
    print(&quot;Does any word start with 'ap'?&quot;, trie.startswith(&quot;ap&quot;))  # Output: True
    print(&quot;Does any word start with 'ora'?&quot;, trie.startswith(&quot;ora&quot;))  # Output: False
    
    # Get autocomplete suggestions for a given prefix
    print(&quot;\nAutocomplete Suggestions for 'ba':&quot;, trie.autocomplete(&quot;ba&quot;))  # Output: ['ball', 'banana', 'bat']
    
    # Delete a word from the trie
    trie.delete(&quot;apple&quot;)
    print(&quot;\nAfter deleting 'apple':&quot;, trie.words())  # Output: ['app', 'ball', 'banana', 'bat']
    
    # Count the total number of words in the trie
    print(&quot;\nTotal Number of Words:&quot;, trie.count_words())  # Output: 4
    
    # Count the number of words with a given prefix
    print(&quot;Number of words with prefix 'ba':&quot;, trie.count_prefixes(&quot;ba&quot;))  # Output: 3
    


    Related Article: Python Data Structures and Algorithms

    Create Quiz

    S

    surajkr_gupta
    Improve

    S

    surajkr_gupta
    Improve
    Article Tags :
    • Python
    • Python-Library
    • python-modules
    • Python-DSA

    Explore

      Python Fundamentals

      Python Introduction

      2 min read

      Input and Output in Python

      4 min read

      Python Variables

      4 min read

      Python Operators

      4 min read

      Python Keywords

      2 min read

      Python Data Types

      8 min read

      Conditional Statements in Python

      3 min read

      Loops in Python - For, While and Nested Loops

      5 min read

      Python Functions

      5 min read

      Recursion in Python

      4 min read

      Python Lambda Functions

      5 min read

      Python Data Structures

      Python String

      5 min read

      Python Lists

      4 min read

      Python Tuples

      4 min read

      Python Dictionary

      3 min read

      Python Sets

      6 min read

      Python Arrays

      7 min read

      List Comprehension in Python

      4 min read

      Advanced Python

      Python OOP Concepts

      11 min read

      Python Exception Handling

      5 min read

      File Handling in Python

      4 min read

      Python Database Tutorial

      4 min read

      Python MongoDB Tutorial

      3 min read

      Python MySQL

      9 min read

      Python Packages

      10 min read

      Python Modules

      3 min read

      Python DSA Libraries

      15 min read

      List of Python GUI Library and Packages

      3 min read

      Data Science with Python

      NumPy Tutorial - Python Library

      3 min read

      Pandas Tutorial

      4 min read

      Matplotlib Tutorial

      5 min read

      Python Seaborn Tutorial

      3 min read

      StatsModel Library - Tutorial

      3 min read

      Learning Model Building in Scikit-learn

      6 min read

      TensorFlow Tutorial

      2 min read

      PyTorch Tutorial

      6 min read

      Web Development with Python

      Flask Tutorial

      8 min read

      Django Tutorial | Learn Django Framework

      7 min read

      Django ORM - Inserting, Updating & Deleting Data

      4 min read

      Templating With Jinja2 in Flask

      6 min read

      Django Templates

      5 min read

      Build a REST API using Flask - Python

      3 min read

      Building a Simple API with Django REST Framework

      3 min read

      Python Practice

      Python Quiz

      1 min read

      Python Coding Practice

      1 min read

      Python Interview Questions and Answers

      15+ min read
    top_of_element && top_of_screen < bottom_of_element) || (bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) || (top_of_screen > articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Campus Training Program
  • Explore
  • POTD
  • Job-A-Thon
  • Blogs
  • Nation Skill Up
  • Tutorials
  • Programming Languages
  • DSA
  • Web Technology
  • AI, ML & Data Science
  • DevOps
  • CS Core Subjects
  • Interview Preparation
  • Software and Tools
  • Courses
  • ML and Data Science
  • DSA and Placements
  • Web Development
  • Programming Languages
  • DevOps & Cloud
  • GATE
  • Trending Technologies
  • Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
  • Preparation Corner
  • Interview Corner
  • Aptitude
  • Puzzles
  • GfG 160
  • System Design
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.
See More

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences