Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Merge two sorted arrays in constant space using Min Heap
Next article icon

Merge two sorted arrays in Python using heapq

Last Updated : 04 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two sorted arrays, the task is to merge them in a sorted manner. Examples:

Input :  arr1 = [1, 3, 4, 5]            arr2 = [2, 4, 6, 8] Output : arr3 = [1, 2, 3, 4, 4, 5, 6, 8]  Input  : arr1 = [5, 8, 9]            arr2 = [4, 7, 8] Output : arr3 = [4, 5, 7, 8, 8, 9]

This problem has existing solution please refer Merge two sorted arrays link. We will solve this problem in python using heapq.merge() in a single line of code. 

Implementation:

Python3




# Function to merge two sorted arrays
from heapq import merge
 
def mergeArray(arr1,arr2):
    return list(merge(arr1, arr2))
 
# Driver function
if __name__ == "__main__":
    arr1 = [1,3,4,5] 
    arr2 = [2,4,6,8]
    print (mergeArray(arr1, arr2))
 
 
Output
[1, 2, 3, 4, 4, 5, 6, 8]

The time complexity  is O(n log n).

The space complexity  is O(n).

Properties of heapq module ?

This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. To create a heap, use a list initialized to [], or you can transform a populated list into a heap via function heapify().The following functions are provided:

  • heapq.heappush(heap,item) : Push the value item onto the heap, maintaining the heap invariant.
  • heapq.heappop(heap) : Pop and return the smallest item from the heap, maintaining the heap invariant. If the heap is empty, IndexError is raised. To access the smallest item without popping it, use heap[0].
  • heapq.heappushpop(heap, item) : Push item on the heap, then pop and return the smallest item from the heap. The combined action runs more efficiently than heappush() followed by a separate call to heappop().
  • heapq.heapify(x) : Transform list x into a heap, in-place, in linear time.
  • heapq.merge(*iterables) : Merge multiple sorted inputs into a single sorted output (for example, merge timestamped entries from multiple log files). Returns an iterator over the sorted values.


Next Article
Merge two sorted arrays in constant space using Min Heap
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • DSA
  • Heap
  • Python
  • array-merge
Practice Tags :
  • Arrays
  • Heap
  • python

Similar Reads

  • Merge k Sorted Arrays Using Min Heap
    Given k sorted arrays of possibly different sizes, merge them and print the sorted output.Examples: Input: k = 3 arr[][] = { {1, 3}, {2, 4, 6}, {0, 9, 10, 11}} ;Output: 0 1 2 3 4 6 9 10 11 Input: k = 2 arr[][] = { {1, 3, 20}, {2, 4, 6}} ;Output: 1 2 3 4 6 20 We have discussed a solution that works f
    7 min read
  • Merge two sorted arrays in constant space using Min Heap
    Given two sorted arrays, we need to merge them with O(1) extra space into a sorted array, when N is the size of the first array, and M is the size of the second array. Example : Input: arr1[] = {10}; arr2[] = {2, 3};Output: arr1[] = {2} arr2[] = {3, 10} Input: arr1[] = {1, 5, 9, 10, 15, 20}; arr2[]
    8 min read
  • Merge two sorted arrays using Priority queue
    Given two sorted arrays A[] and B[] of sizes N and M respectively, the task is to merge them in a sorted manner. Examples: Input: A[] = { 5, 6, 8 }, B[] = { 4, 7, 8 }Output: 4 5 6 7 8 8 Input: A[] = {1, 3, 4, 5}, B] = {2, 4, 6, 8} Output: 1 2 3 4 4 5 6 8 Input: A[] = {5, 8, 9}, B[] = {4, 7, 8} Outpu
    6 min read
  • Sorted merge in one array
    Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Merge B into A in sorted order. Examples: Input : a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA} b[] = {16, 17, 19, 20, 22};; Output : a[] = {10, 12, 13, 14, 16, 17, 18, 19, 20, 22} One way is to merge the two
    7 min read
  • Merging two unsorted arrays in sorted order
    Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list. Examples : Input : a[] = {10, 5, 15} b[] = {20, 3, 2} Output : Merge List : {2, 3, 5, 10, 15,
    12 min read
  • Merge two sorted arrays
    Given two sorted arrays, the task is to merge them in a sorted manner.Examples: Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8} Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8} Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8} Output: arr3[] = {4, 5, 7, 8, 8, 9} Table of Content [Naive Approach] Concaten
    10 min read
  • K-th Element of Merged Two Sorted Arrays
    Given two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays. Examples: Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5Output: 6Explanation: The final sorted array is [1
    15+ min read
  • 3-way Merge Sort in Python
    Merge sort involves recursively splitting the array into 2 parts, sorting, and finally merging them. A variant of merge sort is called 3-way merge sort where instead of splitting the array into 2 parts we split it into 3 parts. Examples: Input: arr = [12, 11, 13, 5, 6, 7]Output: [5, 6, 7, 11, 12, 13
    5 min read
  • K-ary Heap using Python
    Ak-ary heap is also called n-ary or d-ary heap. It is a generalized form of the binary heap structure where each node has up to K children, unlike the binary heap structure with only 2 children. Because of this feature, the k-ary heap is a flexible and efficient data structure for priority queue imp
    11 min read
  • Union of Two Sorted Arrays
    Given two sorted arrays a[] and b[], the task is to to return union of both the arrays in sorted order. Union of two arrays is an array having all distinct elements that are present in either array. The input arrays may contain duplicates. Examples: Input: a[] = {1, 1, 2, 2, 2, 4}, b[] = {2, 2, 4, 4
    15+ min read
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
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
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.

What kind of Experience do you want to share?

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