Merge Sorted Array

by atalaykutlay

Solution for merge sorted array question on Leetcode.

Merge Sorted Array
1class Solution:
2    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
3        """
4        Do not return anything, modify nums1 in-place instead.
5        """
6        left = m-1
7        right = n-1
8        for i in range(m+n-1, -1, -1):
9            if left >= 0 and right >= 0 and nums1[left] > nums2[right]:
10                nums1[i] = nums1[left]
11                left -= 1
12            elif right >= 0:
13                nums1[i] = nums2[right]
14                right -= 1
15        

✨ Code Explanation ✨

This code is a solution to the Leetcode problem titled "Merge Sorted Array." The function takes in two sorted arrays, 'nums1' and 'nums2' and their respective lengths 'm' and 'n'. The goal of the function is to merge 'nums2' into 'nums1' and ensure the result is still sorted. The function begins by initializing two pointers, 'left' and 'right'. These two pointers are set to the end of 'nums1' and 'nums2' respectively. A 'for' loop is then used to iterate through a range of indices from 'm+n-1' to 0, both inclusive, in reverse order. Within the loop, each value of 'nums1' at the current index 'i' is then assigned either the current value of 'nums1' at index 'left' or 'nums2' at index 'right'. If 'nums1[left]' is greater than 'nums2[right]' and both pointers are still within their respective arrays, 'nums1[i]' will be assigned 'nums1[left]' and 'left' will be decremented by 1. If 'nums1[left]' is not greater than 'nums2[right]', then 'nums1[i]' will be assigned 'nums2[right]' and 'right' will be decremented by 1. Once all values have been assigned, 'nums1' will contain the merged sorted array of 'nums1' and 'nums2' and the function will terminate.

Share

Share
Video
A cool 10 sec video.
Share
Detailed
Title, description, and syntax highlighted code.
Share
Simple
Syntax highlighted code with gradient background colored presentation.

Comments

It looks like there is no comment for this snippet. Leave the first one!
You need to login to send a comment.

Similar Snippets

Count Number of Texts
Count Number of Texts

Solution to "Count Number of Texts" question on Leetcode.

Language: python12 months ago
Quicksort in Python
Quicksort in Python

An easy quicksort implementation in Python.

Language: python13 months ago
Second Minimum Node In a Binary Tree
Second Minimum Node In a Binary Tree

Solution to "Second Minimum Node In a Binary Tree" on Leetcode.

Language: python11 months ago