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!

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

Contest Alert

🏆 #CodeEveryDay July 2026

Contest runs July 1 - 31. Complete challenges to climb the leaderboard!

Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In