Skip to content

Latest commit

 

History

History
80 lines (58 loc) · 2.81 KB

File metadata and controls

80 lines (58 loc) · 2.81 KB

🧩 LeetCode 2619: Array Prototype Last

📘 সমস্যা বিবরণ (Problem Description)

তোমাকে JavaScript–এ একটি custom function তৈরি করতে হবে যা Array.prototype–এ যুক্ত হবে।
এই ফাংশনের নাম হবে last() এবং এটি array–এর শেষ element রিটার্ন করবে।

যদি array খালি থাকে, তাহলে -1 রিটার্ন করতে হবে।


🧠 উদাহরণ (Examples)

Example 1:

Input: nums = [null, {}, 3]
Output: 3
Explanation: Calling nums.last() should return the last element: 3.
Example 2:

Input: nums = []
Output: -1
Explanation: Because there are no elements, return -1.
 

Constraints:

arr is a valid JSON array
0 <= arr.length <= 1000

💡 ভাবনা (Intuition)

JavaScript–এ array–এর শেষ element পাওয়া যায় সহজেই:

arr[arr.length - 1]

কিন্তু যদি array খালি হয় (length === 0), তখন undefined রিটার্ন হয়। এই অবস্থায় আমাদের -1 রিটার্ন করতে হবে।

🧮 JavaScript সমাধান (Solution)

/**
 * @return {null|boolean|number|string|Array|Object}
 */
Array.prototype.last = function() {
  if (this.length === 0) {
    return -1;
  }
  return this[this.length - 1];
};

🧠 ব্যাখ্যা (Explanation)

ধাপ কাজ ফলাফল
1️⃣ Array.prototype.last তৈরি করা
2️⃣ this → বর্তমান array–কে নির্দেশ করে যেমন [1,2,3]
3️⃣ যদি length === 0 → খালি array -1 রিটার্ন
4️⃣ অন্যথায় → শেষ element রিটার্ন this[this.length - 1]

🧾 উদাহরণসহ টেস্ট

const arr1 = [1, 2, 3];
console.log(arr1.last()); // Output: 3

const arr2 = [];
console.log(arr2.last()); // Output: -1

const arr3 = [null, {}, "Hello"];
console.log(arr3.last()); // Output: "Hello"

⚡ অতিরিক্ত তথ্য (Extra Note)

  • ✅ Array.prototype–এ মেথড যোগ করা মানে হলো সব array–ই এই নতুন মেথড ব্যবহার করতে পারবে।
  • ⚠️ তবে production কোডে এটি সাবধানে ব্যবহার করতে হয়, কারণ এটি global behavior পরিবর্তন করে।