Create a method that takes a list of Contact records and inserts only those that have both a FirstName, LastName, and valid AccountId. Return the number of successfully inserted contacts using Database.insert with allOrNone set to false to allow partial success.

Examples:

Input: contacts = [Contact(FirstName='John', LastName='Doe', AccountId='001xxx'), Contact(FirstName='Jane', LastName='Smith', AccountId='001yyy'), Contact(FirstName='Bob', LastName='Wilson', AccountId='001zzz')]
Output: 3
Explanation: All three contacts have FirstName, LastName, and AccountId, so all are inserted

Input: contacts = [Contact(FirstName='John', LastName='Doe', AccountId='001xxx'), Contact(FirstName=null, LastName='Smith', AccountId='001yyy'), Contact(FirstName='Bob', LastName=null, AccountId='001zzz')]
Output: 1
Explanation: Only the first contact has all required fields, so only 1 is successfully inserted

Input: contacts = null
Output: 0
Explanation: Null input returns 0

Apex Code Editor

Welcome to Lightning Challenge!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Note

You can test your code by connecting to Salesforce, but to save your progress and earn points, you'll need to create an account. Your solutions and achievements will be tracked automatically once you're logged in.