Загрузка...

Merge Sorted Array | LeetCode | C++ Easy Explanation

📌 Title: Merge Sorted Array | LeetCode | C++ Easy Explanation

🔹 Problem: Merge Sorted Array

🔗 LeetCode Problem:
https://leetcode.com/problems/merge-sorted-array/

📌 Problem Explanation:
In this problem, we are given two sorted arrays nums1 and nums2.

* nums1 has a size of m + n, where the first m elements are valid and the last n elements are 0s.
* nums2 contains n sorted elements.

Our task is to merge nums2 into nums1 so that nums1 becomes a single sorted array.

👉 Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3

Output:
[1,2,2,3,5,6]

---

💡 Approach:

This solution follows a simple strategy:

* Copy all elements of nums2 into the empty positions at the end of nums1.
* After inserting all elements, sort the entire nums1 array.
* Since all elements from both arrays are now present in nums1, sorting gives the final merged sorted array.

👉 Why this works:

* nums1 has enough space to hold all elements from nums2.
* After copying, both arrays' elements are combined.
* Sorting arranges all elements in increasing order.

This is a straightforward and beginner-friendly approach.

---

⏱ Time Complexity:

O((m + n) log(m + n))

Because the entire array is sorted after merging.

💾 Space Complexity:

O(1)

Sorting is performed directly on nums1 without using another array.

---

🧠 Key Concepts:

* Arrays
* Sorting
* STL sort()
* Array Manipulation

---

📝 Notes:

* Very easy and intuitive solution.
* Good for beginners learning arrays and sorting.
* There exists a more optimized two-pointer approach, but this method is simple to understand and implement.

---

🔗 GitHub Repository:
https://github.com/abdulhaque2005

🔗 LeetCode Profile:
https://leetcode.com/u/pDjnXUuCp8/

🔗 LinkedIn:
https://www.linkedin.com/in/abdul-haque78/

---

🚀 DSA Practice Journey:

* 160+ LeetCode Questions
* 40 YouTube Videos
* C++ + STL based solutions

---

#DSA #LeetCode #CPP #Coding #Programming #Arrays #Sorting #STL

Видео Merge Sorted Array | LeetCode | C++ Easy Explanation канала HaqueCodes
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять